About C static libraries

Santiago Peña Mosquera
3 min readMar 10, 2020

--

Why to use libraries

When we code, very often or almost always we reuse code even in small programs, which becomes a tedious process, because the time it’s spent rewriting, and the amount of code that we and the machine have to process. To solve this problem we store this reusable code in libraries, that are nothing more than collection of resources used by computer programs.

How static libraries work

A static library is a container file with several packages of object code files, which in the linking process will be copied and relocated in the final executable file, along with the rest of the object code files. this process is known as a static construction of the target application.

How to create a static library

To create a static library, first we need to compile our c code into object code, using the -c flag of the gcc compiler.

$ gcc -c file_name.c

If we have all the files (C files) wanted to compile in the same directory, we can use the command gcc -c *.c.

After having the object code files using the GNU ar (archiver) program we can create aour library.

$ ar -rc liblibrary_name.a file1.o file2.o

The r falg replace older object files, and the c flag tells ar to create the library if it does not exist.

After an archive or static library is created, or modified, we need to index it. with the command ranlib.

$ ranlib liblibrary_name.a

We can see the content of our library, using the -t flag of the command ar.

$ ar -t liblibrary_name.a

We also can see the symbols of our library with the command nm.

$ nm liblibrary_name.a

Example:

For this example we are goin to generate the library holberton, which contains all the C files showing below

First, we compile all those files with the command gcc -c *.c.

After we get all the object files, can create the library libholberton.a with the command ar -rc libholberton.a *.o

Them we can look at the content of libholberton.a with the command ar -t libholberton.a

How to use static libraries

Now that we have created our static libray, we can use it, as invoking it in the compilation and linking process with the gcc comand and the flags -l and -L.

$ gcc main.c -L/library_path -llibrary_name -o main

-L indicates the path to our library .

-l must be followed by our library name without lib prefix an extention .a.

Although static libraries are widely used, there are two main disadvantages, which are:

  • The size of our exutables files will encrease depending on the cuantitie of functions in our static library that need to be added to it.
  • we must recompile our executable file if there is any update in our static library code.

To solve these problems, shared or dynamic libraries were created, but this will be a topic for another post.

--

--