What is a static library?
In computer science, a library is a collection of modules, which may already be compiled and ready to be used by programs.
Specifically a static library is an archive containing object files ( with ‘.a’ suffix on Unix-like systems).
Why use static libraries
Static libraries allow us to save time when compiling a program. After adding the object codes of the source files that we want in our library, we can then link the library during compilation. We are going to see below how it works.
Another advantage of the static library is that we can share our library with others programmers without sharing the source code.
How they work
The linker makes a copy of all the functions it finds inside the library to the executable program and even of those that are not called in the program. The downside is that this takes space in the memory storage.
How to create them
We can get the object code from a source file at the end of the assembly step (compilation process). We can use the command ‘c’ to stop the compilation after this step and get the object code from all the .c files in the current directory (“*.c”):
In our terminal window, we can use the ‘ar’ command to create a static library. The ‘c’ option creates the library if it doesn’t already exist and ‘r’ allows us to replace older object files with the new ones we add:
Afterwords, we need to index the static library. One way to do it is by using the “ranlib” command. According to its man page, “ranlib generates an index to the contents of an archive and stores it in the archive. The index lists each symbol defined by a member of an archive that is a relocatable object file.”
How to use them
Once the library is created we can easily link it to a program. Firstly we have to pass main.c (the program in question, which will call the other functions and contains main() ) into object file by using the previous command.
Finally, we can do the linking with this command:
- main.o is the object file of the main.c
- “-L” with a . tells the linker to look for the static library in the current directory.
- “-l” option links the lib. Note that we don’t need to put the lib prefix and the .a suffix. This option does it for us.
- myprog is the final executable file.
We can run it by doing ./myprog.