Tuesday, August 18, 2009

Creating shared and static libraries

How to create a shared and a static library with gcc.

The code for the library you want to build

This is the code that goes will be in the library. It is one single function that takes two doubles and calculates their avg value and returns it.


double avg(double a, double b)

return (a+b) / 2;

The header file

Of course, we need a header file.

/* it is very basic example so i don't have any other prototypes or declarations.


double avg(double, double);

Build the static library

A static library is basically a set of object files that were copied into a single file. This single file is the static library. The static file is created with the archiver (ar).

First, calc_avg.c is turned into an object file:

gcc -c calc_avg.c -o calc_avg.o

Then, the archiver (ar) is invoked to produce a static library (named libavg.a) out of the object file calc_avg.o.

ar  rcs libavg.a      calc_avg.o

Note: the library must start with the three letters lib and have the suffix .a.

Creating the shared library

As with static libraries, an object file is created. The -fPIC option tells gcc to create position independant code which is necessary for shared libraries. Note also, that the object file created for the static library will be overwritten. That's not bad, however, because we have a static library that already contains the needed object file.

gcc -c -fPIC calc_avg.c -o calc_avg.o    

Due to some reason, gcc will compliance:

cc1: warning: -fPIC ignored for target (all code is position independent)

It looks like -fPIC is not necessary on x86, but according to manuals , it's needed, so I use it too.

Now, the shared library is created using bellow command

gcc -shared -Wl,-soname,libavg.so.1 -o libavg.so.1.0.1  calc_avg.o

Note: the library must start with the three letter lib and ends with .so for shared library.

The programm using the library

This is the program that uses the calc_avg library. Once, we will link it against the static library and once against the shared library.


#include "calc_avg.h"
int main(int argc, char* argv[]) {
double value1, value2, result;
value1 = 3;
value2 = 12;
result = avg(value1, value2);
printf("The avg of %3.2f and %3.2f is %3.2f\n", value1, value2, result);
return 0;

Linking against static library

gcc -static main.c -L. -lavg -o statically_linked

Note: the first three letters (the lib) must not be specified, as well as the suffix (.a)

Linking against shared library

gcc main.c -o dynamically_linked -L. -lavg

Note: the first three letters (the lib) must not be specified, as well as the suffix (.so)

Executing the dynamically linked programm


No comments: