How to create a static library.

A static library is a collection of object files that are attached to a program when the program is linked. Thus, static libraries are used only when creating a program. Then they do not take part in the work of the program itself.

To create static libraries, there is a special simple program called ar (short for archiver). It is used to create, modify and view object files in static libraries, which are really simple archives.

First of all, to create your own static library, you need to write its implementation. Let’s say that we have several .c files with our functions for our future static library. For example,

Image 1 .c files with the functions in the current directory 0x09-static_libraries

Step 1

First, we will create object files. We will use the commande:

The -c flag tells the compiler to skip the linking step.

Step 2

After compiling the library, the object files will be created, which must be packed into an archive. Remember that the name of each library must begin with the word “lib”, followed by the actual name of the library, in our case “functions”.

The ‘r’ flag tells it to replace older object files in the library, with the new object files.

The ‘c’ — create a new archive; if it exists, overwrite it.

Step 3

Right now we only have an libfunctions.a archive file. To make a full-fledged library of object files from it, we need to add a symbol index to this archive, i.e. a list of functions and variables nested in the library to make linking faster.

This is given by the command:

The ranlib program will add an index to the archive to create a complete static library of object files.

It is worth noting that on some systems the ar program automatically creates the index and using ranlib has no effect. But here you have to be careful when compiling a library automatically using makefiles, if you do not use the ranlib utility, then it is possible that on some systems the libraries will not be created correctly and the platform independence will be lost. So let’s take as a rule the fact that the ranlib utility must be run anyway, even if it has no effect.

To compile our main file, main.c, we need to tell the compiler to use libraries. So that the compiler knows where to look for libraries, it needs to be told the directory in which they are contained and the list of these libraries. The library directory is specified with the -L switch.

In our case the library is in the current directory, so the path to it will be in the form of a dot (-L.). The libraries used are listed with the -l switch, followed by the name of the library without the lib prefix and the ending .a. In our case, this key will look like :

Software engineering student at Holberton School

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store