Static Libraries in C

What are static libraries in C? To understand what a static library is, first we must understand what a library in C does. A library is a file which holds object files, that can be utilized during the linking phase of compilation. The primary advantage of libraries in C is to allow users to link programs without having to recompile them. Therefore, time is saved since all object files are placed into a singular file(the library). A C library ends with a “.a” and is normally indexed. As a result, it is easier to find symbols such as functions and variables inside of them. It is much faster to link a program when the object files are contained inside one organized file, as opposed to multiple files. This is why libraries are vital.

Primarily, there are two types of libraries that are used in C. Static libraries, and shared libraries. In this blog post, I will be describing how to create and run a static library. Static libraries are simply files that contain object files that are linked into the program during linking phase, and are not required during runtime. One creates a static library with the “ar” command, known as the archiver. This command creates static libraries, modify object files inside libraries, and can list file names inside the library.

Above image creates a static library named libutil.a, and places the files util_file.o, util_net.o, and util_math.o inside

The ar command creates the static library, while the r flag tells the program to replace old files with new ones, and the c flag tells it to create a library file if it does not exist. Once the file is created, the library needs to be indexed, which speeds up the symbol checking process during compilation. One can do this, by running the ranlib command.

ranlib indexes the library to speed up symbol look-up during compilation

Now that we know how to create a static library, let’s discuss how to use it. One can do this by adding the name of the library, with the list of files provided to the linker.

Here we see the crawler.c file being linked to the libtseutil.a library

Once the library is linked, we have successfully created our library and linked to a program. Thank you for reading this blog on static libraries.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.