Libraries in C (static & dynamic)

Why should I use libraries ? How do they work ? How to create/use them ?

One of the principal purposes of using a static library for your program is to get more efficiency. In fact, during the compiling time, linking to a library is faster than linking to several individual source files (i.e. bodies of all the functions that are compiled individually).

A good point with dynamic libraries (or shared libraries) is that we can modify source code without recompiling the entire program, in fact, they are linked during the run-time (and not during the compiling time like static libraries). Dynamic libraries have to handle multiple calls to functions during run-time, the program is lighter but less efficient than static libraries.

Technically, Static library (i.e. not modified untill the program will be compiled again) are object files linked with another object to create a final executable file. Those executables usually have a “.a” extension on Unix-like systems and “.lib” on Windows, and have a prefix “lib” by convention (e.g. libexemple.a)

How to create a static library in linux :

In order to create a static library, you will need some command lines I am going to explain below.

First of all, inside the current working directory, we have to use GCC command to compile our C files into object files :

gcc -c *.c

Now, as we said before, library is an archive so we will create an archive file from all object files using the “ar” command :

ar -rc libexample.a file1.o file2.o filex.o

The “c” flag tells “ar” to create the library if it doesn't already exist. And the “r” flag tells it to replace older object files in the library, with the new object files.

After an archive is created, we need to index it. Index will be used by the compiler to speed up symbol-lookup inside the library, and to make sure that the order of the symbols (e.g. functions, variables and so on) in the library won’t matter during compilation. To create, or update, an index, we need “ranlib” command as below :

ranlib libexample.a

Moreover, if you want to list the content of your library, you can use the “t” flag as follows :

ar -t libexemple.a

How to create a dynamic library in linux :

As we did for static library, the following command will compile our C files into object files, moreover, the “-c” flag permits to be sure that *.o files aren’t already linked and the “-fPIC” flag permits to be sure that the code is position-independent:

gcc *.c -c -fPIC

Finally, lets compile all object files into a “-shared” library with the following command:

gcc *.o -shared -o