Thursday, January 31, 2013

Creating a Shared Library in C using GCC

This post is about how to create a shared library in C using the GCC Compiler.
Often we are only used to writing small C programs which might contain small functions, all of which are in the same file. Hence its very easy and straight forward to compile and get it working.

However this is not the case when our program is spread across over in many files. In which case we will have to compile each of them individually and link them together to form a final executable file. So let me walk you through a small example on how to compile a small "Hello World" program which spans across 3 different files.

Let us have 3 files here.
File 1 ==> A Header file (hello.h) which contains the declaration of hello() function
File 2 ==> A source file (hello.c) which contains the implementation of hello() function
File 3 ==> Another source file (main.c) which uses the function hello()

So out task is now here to create the first two files and create a shared library using them so that we can use the function hello() from the shared library in any program then after.

The two files hello.h and hello.c are as shown below:


/* hello.h */

#include
void hello();


/* hello.c */

#include "hello.h"
void hello() {
    printf("\nHellow World!!\n");
}


Now lets build a shared library after compiling them individually using commands below
gcc -c hello.h
gcc -c hello.c
gcc -Wall -shared -fPIC -o libhello.so example.c

In the above command we are creating a shared library named libhello.so
Remember to prefix your library name with "lib" and have an an extension as .so

Now that our shared library is ready, all we are left out with is to create a main.c file where the function hello() is being used and compile and link that file with our shared library.

Here is out main.c file

/* main .c */

#include"hello.h"
int main() {    
    hello();
    return 0;
}


Compile it as below
gcc -c main.c

Now to link this main.c with shared library we can use -L and -l options as below
gcc main.c -L . -lhello

In above command "dot" specifies the current directory. If our shared library was in some other directory then we can specify the path using -L option as shown below
gcc main.c -L <shared_lib_location>  -lhello

And -lhello tell gcc to look for a library named libhello.so


Now that we have compiled and linked our main.c file; we can execute and see the output as below
./a.out 
Hellow World!!

In my next post I shall discuss about make files!!

No comments: