C static libraries

What is a library in c?
A library is a collection of several object files (.o, .obj), that can be used as single entity in a linking phase of a program. it actually means that those files are generated one step before linking, in other words, before creating the executable file.

How static libraries work?
In summary, a static library is a library that is copied in our program when we compile it so once we have our executable file, it has a copy of all that it needs.

How to create them?
First of all, as we said before we have to have the object files ‘.o’ in order to create the library
Note: If you have your function ‘.c’ you have to compile it so you create the object file ‘.o’ (Let’s see how to do this)
gcc -c name_of_the_function.c

As we can see in the example, we have a function called ‘function1.c’ and after compiling it we get the object file being in this case function1.o
In the following example, we have 9 functions and we want to put them in a static library.

The tool for creating a static library is a program called ‘ar’ which stands for “archiver”, we can use the options ‘-rc’ in which the r flag replace older object files in the library with new object files and the c flag create the library if it does not exist.
To create the static library we must execute the following command if we want to put inside the library multiple files we only have to use the wildcard ‘*’
ar -rc library_name.a object_files.o
and we can use the option ‘-t’ in order to display a table listing the contents of the archive.

Now our static library is created correctly.
After creating the library to generate index to archive we can use ranlib
ranlib library1.a
How to use them?
In order to use our library, we need to compile our program using gcc in this way
gcc program.c -L. -lone -o program
with the first flag -L we specify the path in which the library is located so if the path is in the directory we are in we need to add a point ‘-L.’. And with the second flag -l we call the name of the library omitting the prefix ‘lib’ and the extension ‘.a’.
That’s all, after doing the previous steps we are able to run the executable.