Static Libraries in C
Static libraries are simply a collection of ordinary object files; conventionally, static libraries end with the ``.a’’ suffix. This collection is created using the ar (archiver) program. Static libraries aren’t used as often as they once were, because of the advantages of shared libraries (described below). Still, they’re sometimes created, they existed first historically, and they’re simpler to explain.
Static libraries permit users to link to programs without having to recompile its code, saving recompilation time. Note that recompilation time is less important given today’s faster compilers, so this reason is not as strong as it once was. Static libraries are often useful for developers if they wish to permit programmers to link to their library, but don’t want to give the library source code (which is an advantage to the library vendor, but obviously not an advantage to the programmer trying to use the library). In theory, code in static ELF libraries that is linked into an executable should run slightly faster (by 1–5%) than a shared library or a dynamically loaded library, but in practice this rarely seems to be the case due to other confounding factors.
How to create static library
To create a static library using GCC we need to compile our library code into an object file so we tell GCC to do this using -c
gcc -c file.c
or if you want compile all c files in the current directory you have to use de wildcard *, let me show you
gcc -c *.c
Once this command is entered, the corresponding .o files will be present in the directory. We are now ready to create our library file!
Next, we will take all of our .o files and package them into a single .a file.
For a full list of the capabilities of the arcommand, take a look at its man page (man ar) — its able to create static libraries, modify object files in the static library, list the names of object files in the library, and more.
Let’s suppose we will call our static library libholberton.a. We now have our necessary .ofiles. We will run the command:
ar -rc libholberton.a *.o
The -r flag tells the arcommand to create a library if it doesn’t already exist and replaces older existing object files in the library.
The -c flag tells the arcommand to create the library if it doesn’t exist.
We’ve created our static C library!
If we want to see the contents of our library, we can use the ar
option -t
.
ar -t libholberton.a
Whenever files are added to a library, including the initial creation of the library , the library needs to be indexed, which is done with the command ranlib
. ranlib
makes a header in the library with the symbols of the object file contents.This helps the compiler to quickly reference symbols. A large library may have thousands of symbols meaning an index can significantly speed up finding references.
ranlib libholberton.a