How to create an executable by linking multiple object files / c source ?

As we have seen in our another posts “How to create Shared Library in Linux ?” we first created a shared library from multiple object files and then we linked shared library to create a final executable which was using API from that library.

Within this article we will show how to create an executable by linking multiple object files without creating library ( like for example, if you are writing a simple test programs with multiple files )

$ vim first_program.c
#include <stdio.h>
#include "header.h"

void function1(void) {
        printf("This is function1\n");

Here, we have to create also an header, which has a declaration of function1, which will be used by main program,

$ vim header.h
#ifndef __HEADER_H
#define __HEADER_H
void function1(void);

Now, lets write a main program which is using this function1 as,

$ vim main.c
#include <stdio.h>
#include "header.h"
int main(int argc, char *argv[]) {
        function1(); //call function1 from first_program.c
        return 0;

Now, we can create a final executable by two ways,

1. Create an object files of every program and link those object files to create final executable as,

$ gcc -c first_program.c
$ gcc -c main.c

Above two commands create two separate object files first_program.o and main.o which we can then link to create executable as,

$ gcc -o main_linked_using_object_files main.o first_program.o

2. Link source files using single command to create executable,

$ gcc -o main_linked_using_c_code main.c first_program.c

Both ways create an executable which can be executed as,

$ ./main_linked_using_object_files
$ ./main_linked_using_c_code

If you want to understand more about linking, refer our atticle at “Understanding compilation stages – Preprocessor, Compiler, Assembler, Linker, Loader

How to push or commit the code in t... x
How to push or commit the code in the Repository GIT

Leave a Comment

Sign up to our newsletter!

ADB Commands Android Android Applications Android Build system Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia NDK / Middleware / HAL Operating System Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto Embedded Linux