Tuesday, November 23, 2010

create shared C library

How to create and use your own shared C library using gcc? This can be done in 4 steps.
  1. write your library code, say sum.c with header file sum.h, and save them in your library folder, say ~/local/lib for the source, and ~/local/include for the header file.

  2. compile it using gcc

    gcc -I ~/local/include -c sum.c

    This will produce a object file sum.o

  3. create a static library named "hash", do

    ar rcs libhash.a sum.o

    More than one *.o files can be included in single library

  4. you are ready to use it by :
    • include the "sum.h"
    • compile it using gcc -I ~/local/include -L ~/local/lib -lhash ...
    To save typing -I xxx and -L xxx every time to use the library, save the path for auto lookup by adding the following lines to ~/.bashrc or ~/.bash_profile:

    # for header files
    export C_INCLUDE_PATH=~/local/include:$C_INCLUDE_PATH
    # for linking library
    exprot LD_LIBRARY_PATH=~/local/lib:$LD_LIBRARY_PATH
    export LIBRARY_PATH=~/local/lib:$LIBRARY_PATH
For more readings on differences of shared and static library, see here.

0 comments:

Post a Comment