C static libraries

Cristian Fayber Pinzon Capera
3 min readMar 6, 2021

What you need to know about static libraries in C

Whait is it?

A is a compiled object file containing all symbols required by the main program to operate (functions, variables etc.) as opposed to having to pull in separate entities.

What contain?

This could be classes, functions, procedure, scripts, configuration data and more.

Why I use this?

A library can let interact with the OS or contain a collection or mathematical or logical operations or do something else what I needed with what was mentioned above.

How they work

Using a static library means only one object file need be pulled in during the linking phase. This contrasts having the compiler pull in multiple object files (one for each function etc) during linking. The benefit of using a static library is that the functions and other symbols loaded into it are indexed.

This means instead of having to look for each entity on separate parts of the disk, the program need only reference a single single archived object (.a) file that has ordered the entities together. As a consequence of having one ordered object file, the program linking this library can load much faster.

Because the static library object (.a) file is linked at the end of compilation, each program that requires this library must have it’s own copy of the relevant library. Unlike the static library, a single dynamic shared library can be loaded into memory at run-time and be accesible to other programs linked to the same library. More on dynamic libraries in a future post.

How to create them

1- I need to create a header file, in this case named holberton.h, It will contain only the prototypes in this case we are talkin of functions. Is really necessary put the corresponding .c sources files on the same directory where is the header file.

2- Batch compile all source (.c) files. Use the -c option so that compiler doesn’t link the object files yet but instead creates counterpart object (.o) file for each source (.c) file.

gcc -Wall -pedantic -Werror -Wextra -c *.c

The verifying flags are not mandatory for this command.

3- Archive all of the object (.o) files into one static library (.a) file. Use the command option -r to ensure that if the library (.a) file already exists, it will be replaced. The command option -c should be used so that if the file doesn’t exist, it will be created.

ar -rc libholbie.a *.o

The static library in this example will be named libholbie.

libhobie.a was created on the current directory

4- Move the library (.a) file into the same directory that the entry-point file resides. In the case of have other ubication.

5. Now, instead of having to include all relevant file names in the compilation command, only the library (.a) file need be referenced.

--

--