Home > Gnu/Linux > How to create static and dynamic libraries with gcc

How to create static and dynamic libraries with gcc

February 16th, 2009

This is an exercise I did   today. I  am documenting it for my own reference.

The problem was simple.

Create a library with functions.

add(int,int) and sub (int,int)

and then use the library  in another program.

Here is the code


#include “a.h”

int add( int a,int b)

return (a+b);
int sub (int a, int b)
return( a-b);

Here is the header

/* a.h*/

int add(int,int);
int sub(int,int);

Compile add.c to get add.o

gcc -c add.c 

You will have an object file add.o .

Now  create a static library  with

ar rcs  libadd.a add.o

If you have a program which uses functions from your new library as below

/*  main.c */

#include “a.h”
int main()
printf (“%d\n”, add(5,10));
printf (“%d\n”, sub(10,5));
return 0;
You can link against  our new  library  like this.

gcc -o main main.c -L. -ladd

( Note the -L. and -ladd. -L. say that look for library in current directory and -ladd says that the name of the library is libadd.a)

For creating dynamic libraries, first compile the file containing library as below.

gcc -c -fPIC   add.c


 ld -shared -soname libadd.so.1 -o libadd.so.1.0 -lc add.o

 ln -sf libadd.so.1 libadd.so

/sbin/ldconfig -v -n .

( Dont forget .)

Now you are ready to use the library

gcc -o main  main.c -L. -ladd

Categories: Gnu/Linux Tags:
Comments are closed.