C Static Libraries

H_e_d
Use of Static Libraries

--

Static library is a tool containing multiple object code. The objects from the library will be extract from your linker to be used by your program at run time. This is the process of static linking and it will make your program independent for future uses but larger in size.

Interest of using Static libraries :

Imagine making a series of C function for useful tasks to solve a problem. Later on, facing an other project you find out that the old functions could be useful. Instead of remaking or copying it one after the other you make a static library made out of every functions used before as already compiled objects.

Whereas static libraries rise the size of the executable file as it becomes part of the executable file. The use of Dynamic library is often consider as more practical as it remains separate from the executable file.

Creating a Static Library :

To create your own static library made out of your C files you must firstly creates objects files using compiling at assembling state without linking.

You can do so using the gcc command with -c flag like so :

gcc -c *.c

This will create object file for every files ending with .c suffix.

:/tmp/static$ ls
2-strlen.c 3-puts.c
:/tmp/static$ gcc -c *.c
:/tmp/static$ ls
2-strlen.c 2-strlen.o 3-puts.c 3-puts.o

Once we have our object files we can use the ar command which can creates, modify and extract members of an archive. You can do this using the -rc flag allowing to (c)reate and (r)eplace older files.

Notes that the library file takes by convention the prefix “lib” and suffix “.a”, like so :

:/tmp/static$ ar -rc libtest.a *.o*
:/tmp/static$ ls *.a
libtest.a

You can list symbol of objects files in your library using the nm command.

:/tmp/static$ nm libtest.a2-strlen.o:
0000000000000000 T _strlen
3-puts.o:
U _GLOBAL_OFFSET_TABLE_
U putchar
0000000000000000 T _puts

Or if you simply want to see a list of your object file you can use ar -t for listing tables of the archive content.

:/tmp/static$ ar -t libtest.a 
2-strlen.o
3-puts.o

If you wish to create an index to the archive that will be stored inside the archive you can use ranlib command.

Now that we have our static library ready let us see how to use it for compiling a new program.

Use of Static Library :

After we created a header file (holberton.h) which contains our c functions declarations. We can try to compile the following program main.c using our library.

We can use the -L gcc flag to add the path to the library like so :

:/tmp/static$ gcc main.c -L. -ltest

Note that it is only require to use the letter l as prefix and there is no need to add the .a suffix from the library name.

Let’s execute :

:/tmp/static$ ./a.out 
Holberton
9

Seems like everything worked out, the linking could access the objects from the library.

--

--