Static libraries in C

Katherine De La Hoz
3 min readOct 13, 2020

--

To better understand what a static library is, it is important to be clear about the simple concept of a library. A library also defined as a library is nothing more than a set of books, you can access these books through a reference. Something similar happens with libraries in C; We create static libraries that contain files with functions that we can access by referring to them, in this way it would not be necessary to create a file or a commonly used function every time we need to make use of it, but it will be stored in a library.

Below you will find an example of how to create a static library, first it is important that you know that static libraries have an .a extension, that the object files have a .o extension and that the files that contain the functions before compiling will have a.c extension.

The first thing you should do is create a folder called project and locate yourself in this folder through the commands:

mkdir project
cd project

Then create your files, I will use vim but you can do it with any other editor:

vim add.c
vim subtraction.c
vim multiplication.c
vim division.c

Later compile your files with the following command:

gcc -c * .c

To check that the operation has been successful, list your files by extension:

ls * .c will show you all your original files

Through ls * .o you will be able to see the files generated after compilation and if you type ls you will be able to see them all.

With your files created and compiled now, you can create your static library by typing the following command:

ar rc library.a * .o

You have created a library called library with extension .a that contains all the .o files found in the current directory. You can see this file and type ls and you will find more details by typing ls -l.

After creating your library, it is necessary to index the generated file, because these indexes will be used later by the compiler to speed up the search for symbols. To do this you must type the following command:

ranlib library.a

You can see the content of this library through the following command:

ar -t library.a

Finally, if you want to see a list of the functions of the created objects, you can do it with the following command:

nm library.a

Where the first element is the name of the .o file, a ‘T’ indicates that this function is defined in the object file and the zeros before the symbols show that the memory addresses have not yet been placed.

As you can see, static libraries are very easy to create and very useful when coding.

--

--