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

Follow Lynxbee Posts with Google News

Leave a Comment