Static Libraries in C : all you need to know
Libraries are a powerful tool for developper. in this article we will go through various topics : why using static libraries, how to create them, how do they work, how to use them…
What is a static library ?
A static library is a file, stored in object code, used to store functions, variables, classes etc… that you may want to use when building a new program. When you’re compiling your program, you don’t have to include all the files containing the used functions, you just need to add the librairy itself.
This allows us to reuse some already existing code and, as importantly, to link to programs without having to recompile its code, saving recompilation time.
There are 2 types of library used in C : static or dynamic ones. In this article we will only talk about static libraries.
For a better understanding, let’s take a step back and explore the compilation process in C
The compilation process is in 4 steps. During the last step, the linker will take as an input the Machine code and will add any Static library object code in order to produce the executable final file. The linker will copy the needed code of the library to our object file
How to create a static library ?
To create a static library, or to add additional object files to an existing static library, use the program ‘ar’, which stands for ‘archive’. This command can be used as well to list the name of object diles in the library.
After having create object files of the various functions you want to include, using gcc -c command (the -c option will stop the compiling process just before the linking phase and produce .o machine code files), you can just type the following command :
This will create a library called libtest.a from all the .o files that are in the current folder. The ‘.a’ extension still stands for ‘archive’. The option -r stands for “Insert the files member… into archive (with replacement).”. The option -c stands for “The specified archive is always created if it did not exist, when you request an update”
If needed use the ‘ranlib <libtest.a> to index the library, or add -s option when running the previous ar command line
Checking the created library
The files used to create the library can listed using the command ar :
The function included in the library can be listed using the command nm:
How to use your static library
As seen previously, you can use a static library by invoking it as part of the compilation and linking process when creating a program executable.
Using gcc compilation program, you just need to use the special
-l flag, leave out the prefix and
.a suffix. The linker attach these parts back to the name to create a name of a file to look for. You need also to use the
-L to precise the library location.
This command will create an executable called ‘main’, from the main.c file, using as well the library ‘libtest.a’ functions.