C static libraries
What is a static C library and why use it?
A static library, is a collection of object files grouping codes (functions, …) that are linked into the program during the linking phase of compilation. That allows the user to use predefined features in order to gain some time and to reduce the time of compilation too. Indeed, a library allows to manage automatically repeated tasks without having to copy them each time, just invoking functions the user is needing. The object files are directly linked in the final executable. That is the characteristic of a static library.
How to create a static library ?
To create a c static library, we need a list of .c files to compile with the GCC command :
Then, when we have our object files with the .o extension, we will use the archive program (ar) to create our static library (we will name it “libmy.a” here) :
Our library is now created (but if library already exists, the files in it will be replaced if there are more recent files).
Get Lucie Leroty’s stories in your inbox
Join Medium for free to get updates from this writer.
After creating our static library, we have to index it. The compiler use it to go faster with the research of the symbols in the library. To index, we will use the command “ranlib” :
How to use the library ?
To use the library in our program, we have to invoke it. To do this, we will create a file “main.c” that contains our program. For example :
and we will compile it with the following command :
Note that we don’t put the “lib” prefix and “.a” extension. Once done, we can execute our program doing :








