Sunday 9 September 2012

How to Create Dynamic Library in Linux

Step1: implement the library source. Let us assume there are two files namely one.c and two.c each implementing one function as follows
$ vim one.c
#include<stdio.h>
void fun1(){
printf("This is function 1\n");
}
 
$ vim two.c
#include<stdio.h>
void fun2(){
printf("This is function 2\n");
}
 
Step2: compile the sources to generate relocatables. Relocatable binary is created in two forms
position dependent : in this relocated code is bound to offset
position independent : in this relocated code is not bound to offset, because of which sharing of libraries among multiple applications becomes easy.
Preferably we compile them to get position independent relocatables because of some advantages (will cover latter on).
Note: ‘.so’ is the extension for dynamic libraries.

$ gcc -c -fpic one.c 
        ( to create a relocatable one.o )
$ gcc -c -fpic two.c 
       ( to create a relocatable two.o ) 
$ gcc -shared -o libmyown.so one.o two.o
        ( libmyown.so is the name of the dynamic library to be created )
         - shared flag used to create a shared library 
$ gcc -I ./ test.c -o testdynamic ./libmyown.so 
         - I option to let the compiler to check for "mylib.h" in current working directory
         
$ ./testdynamic
This is test to create own library
This is function 1
This is function 2

No comments:

Post a Comment