Static Libraries

Lizzie Turner
2 min readFeb 12, 2018

--

https://xkcd.com/1579/

Static libraries can seem confusing and unnecessary at first, but are actually quite simple to understand as long as you know the what, why, and hows.

What are static libraries and why do you use them?

Libraries are files containing the object files of various programs that are used to make compilation much faster. In C, there are two main types of libraries: static and dynamic. Dynamic libraries, which we won’t concern ourselves with today, are linked in two places, making them extremely small and fast. Static libraries, on the other hand, are specifically called in the linking phase of compilation.

How are they created?

Creating static libraries is a multi-step process:

  1. Compiling the relevant .c files to the object file phase using:
$ gcc -c file1.c file2.c file3.c

2. Archiving the object files into a library with:

$ ar rc libname.a file1.o file2.o file3.o

From there, you will find the appropriately named library (identified by a .a suffix) in your directory.

3. Indexing the library, as needed

$ ranlib libname.a

Indexing is used to later speed up the compiling process, as well as to ensure that various symbols can be read and identified in any order. On some systems, the archiver (which may or may not be ar) contains an indexer; however, it’s good practice to include the indexing step anyway.

How do you use them?

To use a library, add the -l flag, followed by the library name, to the compile command:

$ gcc main.o -l -name 

Note that we no longer need the lib prefix or .a suffix in the library name. Also of note is the fact that we are compiling object (.o) files, not .c files.

--

--