All that you need to know about “C” static libraries.

Omaryahia
3 min readFeb 28, 2021

“I have always imagined that Paradise will be a kind of library.”

Jorge Luis Borges

What is a static library?
The static libraries are pre-existing code that is compiled and ready to use, for example, if you are working on a large project and you have multiple personalized functions you can create a library with all of them and use them in different projects.

Why use static libraries?
By creating a static library you can place all the functions that you are going to use in just one place as a result this is going to save you a lot oftime and is going to make your code more organized.

How to create a static library?
First of all, we need to use GCC (GNU Compiler Collection) to compile the functions that we have into object mode, to do so we need to place this code into shell :

That is going to compile into objects (.o) all the functions that we have ending in “.c”.
Now to create the library we need to use the tool “ar” (archiver) with the flags “-rc” this is going to create and replace the older files where needed.

That is going to add all the object files to the library that we are creating.
To complete the process we just need to use the command “ranlib” to index our library.

If we want to see the contents of our library, we can use the ar option -t.

Now that we have created our static library, we need to add the library name to the compilation and linking process of our main file, as we are using GCC we need to add two flags, the -L that is used tell the linker that the library can be found in the current directory and -l in front of our library name to link the library to our file.

That’s it ! now you can execute your main file.

--

--