C Static libraries

Luz A. Perdomo
2 min readMar 2, 2020

--

Why use libraries?

As human knowledge has grown thousands of years, we have gathered this knowledge in libraries across the world. These libraries contain the result of millions of experiments, discoveries, and validations. Contain the effort to pass ideas to new people so they can be used whenever they need it.
This wonderful concept moves across software development too. Across the globe, millions of developers have already created billions of functions and constants to solve all kinds of problems. Some of these are shared, discussed and refined for the use of other developers in the need to solve similar problems with a variety of data.
In C language the most common sharing method of these libraries is by the creation of static libraries.

How do they work?

Ever wondered what “#include <stdio.h>” meant whenever you used it?. Well, basically “stdio.h” is a static library that was complied with all the basic functions you need to interact with the standard I/O.
This library does not contain the source code of the functions but a reference similar to the header files with an index of the methods, their params and the type of value that they return. These references are used in compilation time to mix you compiled code with the one already compiled in the static library, resulting in an executable file that has both methods working with the ones contained in the static libraries.

How can we create them?

In order to create a static library first you need to use GCC with the option “-c” and the .c file that you wish to add to the library:

gcc -c my_lib.c

This will create an archive with “.o” extension, that we will need to pass over to “ar”, a command that handles the creation, modification, and extraction of archive files:

ar -rc my_lib.a my_lib.o

This will result in a static library file that we can use at will in any other C project without having the need to know or modify its source code.

How to use them

We already learned how to create new libraries, but now let’s check how to use them.
First, we would like to move our library to or project directory. Then, inside the directory, we would reference the file directly in GCC at the executable creation process, something like:

gcc main.c -l my_lib -o main

This will create a “main” file that will use both the code of our “.c” files and the one of the static library.

--

--

Luz A. Perdomo
Luz A. Perdomo

Written by Luz A. Perdomo

0 Followers

I’m Lily oWo

No responses yet