Static Libraries in C Language
Jonatan Mazo
Frontend Developer with 3+ years of experience | React | TypeScript | Next.js | Node.js | MongoDB | Python | Rust | software engineer | Open to new knowledge
Why we use them?
In C programming, static libraries are used to solve several points of the compilation; One of them is to optimize the code in our .c files, and the most common is to optimize the compilation time in large projects.
How they works?
basically it works like a whole group of tools created in order to reduce and optimize the compilation time so that the processes do not have to call standard rambling libraries, but compile only one in a single package, as the previous image shows. In this image we see how a static library is created, based on .c files and .o files.
How to create them?
to create a static library you need two types of files, some .c and others .o, on UNIX systems, we can compile the .c files to generate the .o files that we need to create the static library, for this we can use the GCC compiler with the help of arguments and flags, such as:
This command will create the .o files from the .c files that are in this directory, and with these .o files, we can create our library with the following command:
ar -rc nameoflibrarie.a *.o => The syntax is: the command and its flags, then the name that we will give it finished in an "extension" .a and finally the files we need, in this case the * will bring us all the .o files. With this command we can generate our static library for our project.
How to use them?
Finally we can use it in our project, for this it is simply to add it when compiling our main file and that's it. For this we use the following command:
but first you have to index the library so that the compiler can add it to the moment of linking all the files, and this is done with the command: "ranlib mylib.a"
Thank you for reading :)