Static libraries in C

Edy Yazmin Giraldo
3 min readJul 14, 2021

--

Photo by Erik Mclean on Unsplash

Static libraries are collections of object files grouped in a single file, usually with the prefix “lib” and .a extension, that are linked into the program during the linking phase of compilation.

Just think is easier to link object files that are stored and ordered in a library than having to look for and review every single file for separate at the time of compilation. Also, it’s easier to find symbols like functions and variables because they are normally indexed.

How to create them?

First, you have to put all your source files (.c) into a directory.

Then, you have to compile them using the -c flag so the compiler create the object files (.o) for each source file.

After that, you just have to creates a library with the ar command and store the object files (.o) into it. As I said before, usually a library name starts with “lib” and has a .a extension.

Use the -r flag to ensure that if the library file already exists, it will be replaced. Also, use the -c flag to create the file if it doesn’t exist.

After the library is created, you need to index it so the compiler can look for the symbols in the library really quickly. Also, it will ensure that the order of the symbols won’t matter in the process of compilation.

You can create or update the index with ranlib command:

Now you are ready to use your static library!

How to use them?

Let’s create a program to see how our static library will work:

main.c

Our header file holberton.h contains the declarations of the objects defined in the library and they will tell the compiler how to call the function. So, when we are compiling, we call the library:

We use -l before the library name, so the linker will look for the library libholberton.a as lholberton, in the current directory (-L.) and link it to the program, resulting in the executable file: alive.

Now we can run alive:

And it works!

--

--