Thursday, January 13, 2011

creating shared library with simple example

1.create a separate folder to try this examples.

2. create the a main c file , another two c files which contain the functions used in the main file.

3. create the relative header file.
4.create the include folder and move your header file into that.
5.create the lib folder where we are going to place the our shared library.
6.say for example our files named as
main.c
func1.c
func2.c
lib/
include/

7.create the object file for both func1.c and func2.c using the below command

    gcc -Wall -fPIC -I include/ -c func1.c
    gcc -Wall -fPIC -I include/ -c func2.c

options:

-Wall:- include warnings
-fPIC:- Compiler directive to output position independent code, a        characteristic required by shared libraries

8.create the shared library using the following command.

    gcc -shared -Wl,-soname,libfunc.so -o libfunc.so *.o

options:

-shared:-Produce a shared object which can then be linked with other objects to form an executable.
-Wl:-Pass options to linker(eg--soname,libfunc.so)

9.move that created library file to lib folder
10.create  the  final executable using command

     gcc -Wall -I include/ -L lib/ -lfunc  main.c -o  main

11.normally when executing the final executable file, linker will look into the  /lib, so we have include our library path in the default searching path.


   export LD_LIBRARY_PATH=/path/to/our_lib_folder
12.now run the final executable..

No comments:

Post a Comment