C static libraries

Juan Pablo Montoya
3 min readOct 12, 2020

--

Let’s start by defining what Static libraries are, and then why we should use them.

What are they?
There are two types of libraries, the static ones and the dynamic ones (we will only talk about the static ones). A static library is a file that stores the ‘.c’ file objects that we want to pass to it.

Why should we use them?

To begin with I will make an example.

Let’s say we want to use two or more functions of our own that we create in different files, in order to use those functions we must compile all the files, which takes time, and can make the compilation process slower, that’s where the libraries come in.

In the library we can put all the objects of the files that we want to use.

Let’s say we want to use two or more functions of our own that we created in different files, in order to use those functions we must compile all the files, which takes time, and can make the compilation process slower, that’s where the libraries come in.

In the library we can put all the objects in the files that contain the functions we need, which will accelerate the compilation process because the libraries have a very efficient method to index the objects.

How to create a Static Library?

Creating a static library is simple, there’s two key commands that help us with this task, these commands are ar (for archiver) and ranlib. Now let’s start creating a Static library and explain how each command is working.

ar -rc libexample.a file1.o file2.o file3.o

Okay so in the command above we can see some new stuff, there’s come flags ‘r’ which tells the command to replace older object files in the library, with the new object files. And the ‘c’ flag that is telling the program that if the library doesn’t exists then create it.

‘libexample.a’ is the name of our library, you can name it however you want, and the ‘file1.o’ ‘file2.o’ ‘file3.o’ is saying the command to add those ‘.o’ object files to the library (Note: if you don’t have the .o object of you program, you can compile it with gcc -c [filename.c]).

Now that we have our library libexample.a we have to index the object files inside of it, to do that we can use the other command ranlib.

ranlib libexample.a

That command will index all the contents of our program so when we’re compiling the process of linking is easier.

--

--

Juan Pablo Montoya
Juan Pablo Montoya

Written by Juan Pablo Montoya

Software Engineer student at Holberton School

No responses yet