Saturday, April 24, 2021

How to create and Link Static and Dynamic Libraries

Let’s try to create a math library with two functions add and sub.

// add.c

int add(int x, int y)

{

     return x+y ;

}

//sub.c

int sub(int x, int y)

{

     return x-y ;

}

//main.c

#include <stdio.h>

int add(int, int) ; // you can create a header file

int sub(int, int) ; // and put these

int main(int argc, char **argv)

{

     printf("%d\n", add(5,7)) ;

     printf("%d\n", sub(5,7)) ;

     return 0 ;

}

Now compile it with -c option

gcc -c add.c sub.c

so you will get the object files add.o and sub.o


Creating and Linking a Static Library

Use the ar tool

ar crv libzmath.a add.o sub.o

see the content of

ar -t libzmath.a

Now statically link it like

gcc -o test main.c -L. -lzmath

or

gcc -o test main.c .libzmath.a


Creating and linking the dynamically linked library (shared object)

Again compile while generating Position Independent Code

gcc -c -fpic add.c sub.c

-fpic option is for Position Independent Code

Create the shared library like the following:

gcc -shared -o libmymath.so add.o sub.o

Remember with gcc, all the .so files must start with "lib".

So if library file is libmymath.so, then you have to link it like with the –l option like -lmymath

gcc -Wall -o test main.c -L/home/swarup/work/c -lmymath

-L option is to specify the location where my libmymath.so is present.

Now running ./test may not work, because the .so file is not in the path where linux is looking for to load it. It first searches /usr/local/lib, /usr/lib and so on. So for the ld to work, we need to provide the library path in the environment variable LD_LIBRARY_PATH. We do it like:

export LD_LIBRARY_PATH=/home/swarup/work/c:$LD_LIBRARY_PATH

Note: You can see all the standard libraries in the directory /lib/x86_64-linux-gnu. The functions like printf are part of libc.so.xxx