Static libraries in C language

Daniel V.
3 min readJul 4, 2020

They are collections of object-files grouped into a single file usually with a .lib or .a extension, accompanied by header files, usually .h, containing the declarations of the objects defined in the library.

In other words a library contains one or more functions with their procedures to be used in an executable

Why use libraries?

Libraries are very useful when verifying that some pieces of code (functions and classes) can be used by different applications.

Therefore, it is common for entire teams of developers to build their own toolkits in the form of static and other libraries, thus becoming part of the development resource arsenal.

How they work?… How to create them?

2. Process

after the compiler generates the program’s file-object, it is ready to link it to the standard library using the “ar” command as we will see next

first we need to compile our .c files into file objects using GCC and the -c flag with the following command which tells gcc to convert all .c files in the current directory into file objects

gcc -c *.c

After that we use the command ar to create our final static library, which tells ar to create an archive (flag c) and to insert the objects, replacing older files where needed (flag r) .

ar -rc libholberton.a *.o

After an archive is created, or modified, there is a need to index it. This index is later used by the compiler to speed up symbol-lookup inside the library, and to make sure that the order of the symbols in the library won’t matter during compilation

The command used to create or update the index is called ‘ranlib’, and is invoked as follows:

ranlib libholberton.a

If we want to see the contents of our library, we can use the -t flag.

ar -t libholberton.a

We can also view the symbols in our library, using the nm command, which lists the symbol value of each symbol, the symbol type, and the symbol name of the object files.

nm lib_test.a

now we can link our library in the step of compiling a program with the following command: (the flag -L specify the path to the library which in this case is the current working directory, -l specifify the name of the library without the lib.

gcc main.c -L. -lholberton -o principal

And now we can use the library, running the program:

./main

Note: if the library code is updated, the program must be recompiled with gcc; every program that uses static libraries contains a copy of it in its executable which is very inefficient.

And that’s it all

Have a nice day :)

--

--