Static Library

Ariana Bibiano
3 min readOct 14, 2019

--

In the C programming language, a library is a collection of items (functions, variables, etc.) that are required by the main program in order to operate. The purpose of a library is to be able to reuse functions without having to manually copy and paste the functions into your new programs. Instead you can just compile them into a library and call them from the library.

What is a static library?

A static library is a collection of object files (file names with the .o extension) that are loaded near the end of compilation before the linking phase. (Need a refresher on compilation? Check out this post.) Static libraries start with ‘lib’ and end with a .a extension (e.g. libholberton.a) which is short for archive. The result of statically linking, is an executable file where the library code is stored within it rather than in separate files.

How to create a static library

In order to create a static library we first need to compile our library code into object file using the gcc command followed by the -c option. The -c lets the compiler know to halt the compiling process right before linking.

gcc -c *.c

The files that result are object files (files with the .o extension). And once we have these object files we can then use the ar command, which is short for archiver. An archive is simply a single file that holds a collection a files within it.

ar -rc libholberton.a *.o

The r option tells the archiver to replace older object files with the new object files and the c option tells it to create the library, if it doesn’t already exist.

The following step is to index the archive and this is achieved through the ranlib command. The purpose of indexing an archive is so that the compiler can quickly reference symbols and speed up compilation time.

ranlib libholberton.a

In order to see the contents of our library we will need to use the ar command again but this time followed by the -t option. The -t option just means to display a list of the files in the archive.

ar -t libholberton.a

To view the symbols in our library we would have to use the nm command and it lists the object files by their symbols name, value, and type.

nm libholberton.a

Our static library has just been created! Now on to how to use it.

How to use a static library

We now have our static library libholberton.a we can use it as part of the compilation process to create an executable program.

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

The above means that we are turning the file ‘main.c’ into an executable program name called quote. The -L option specifies the path to the library and the . means current directory. The -l followed by holberton is the library we created earlier (libholberton.a) just without the lib prefix and .a suffix. And the -o option changes the executable file name to quote.

And to run the executable program quote we will just use a period followed by a forward slash.

./quote

--

--