What is a C Static Library?

Maher Ben Dada
4 min readJul 14, 2021

In the C programming language, a static library 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.

Static libraries aren’t loaded by the compiler at run-time; only the executable file need be loaded. Static library object files instead are loaded near the end of compilation during its linking phase.

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.

To create a static library:

  1. Put all relevant files into one directory including the header (.h ) file containing prototypes for the relevant entities. Make sure that the header (.h) file contains the macros #ifndef <HEADERFILE>_H and #define <HEADERFILE>_H at the top and #endif at the bottom so that the header file is only defined once instead of each time it is called.

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.

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.

4. Move the library (.a) file into the same directory that the entry-point file resides.

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

In the end, the static function tool is a great boon as it not only offers a simplified compilation process and fewer resource use, but also reduces the programs size taking up less space on the disk.

--

--