Static Libraries in C
Libraries make life easier.
A library file contains a collection of functions and declarations for use by other programs and programmers.
In this post we will be focused on static libraries.
Why use libraries?
A static library is a file that can be used as a single entity in the linking phase when compiling a file. they are collections of object files that are linked together when a file gets compiled into an executable file.
The benefit of using a static library is that the functions and other symbols loaded into it are indexed and the program need only reference a single single archived object (.a) file that has ordered the entities together.
How they work?
When we compile a source file we get an object file. Depending on our platform its extension .o . A static library is basically a collection of object files, kind of like a .zip file but probably not compressed. The linker, when trying to generate an executable tries to resolve the referenced symbols, i.e. locate in which object file (be it in a library or otherwise) they are defined and links them together. So, a static library may also contain an index of defined symbols in order to facilitate this.
How to create them?
1-The first step is determining which functions we would like to include in our library and preparing them for the archiver.
2-Once this command is entered, the corresponding .o files will be present in the directory.
3-Now we have a list of object files from our C files that are going to be used in our static library. Our next step is to create the static library using the ar
program with all of our object files or .o
files.
4-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.
How to use them?
Now, instead of having to include all relevant file names in the compilation command, only the library (.a) file need be referenced.