Static libraries in C, what they are and how to create your first one
Why do libraries exist?
Libraries exist in computer science because developers need to save time and efforts by reusing code, that means that if there are proven and confident (without bugs) functions, a programmer doesn’t need to reinvent the wheel, just add that code to new ideas.
Libraries are collections of functions which can be called from a program, and this can be done by embedding those libraries in the linking process when compiling the program. Libraries can come from your own creations or from open source code.
What is a static library in C?
A static library is a group of object files linked directly into the final executable of a program, that will remain unchanged unless the program is recompiled. The group of object files before the linking lives in an archive (.a) file written in machine code that is obtained from (.o) files which are obtained from (.c) files where are the codes of the functions. That implies that are needed three steps to generate an executable file with a static library into it.
Another useful step is to generate an index to the contents of the (.a) file before the compiling because this will reduce the time of the process. That index will be in the (.a) file and helps in the finding of the symbols of the functions.
How to create and use a static library?
First of all, it is needed to have all (.c) files in a directory to be sure the library will have only the functions that will be needed,
next, run the next command to create (.o) files:
gcc -Wall -pedantic -Werror -Wextra -c *.c
then, by running the command: ar -rc libholberton.a *.o the library (.a file) is created.
Now, it is the time to generate the index of the library with the command:
and it’s possible to see the index with the command: nm -s libholberton.a
After that, the library can be used linking it to a program (main.c) during the compilation process executing the following command:
gcc main.c -L. -lholberton -o quote
and finally executing the resulting file it’s possible to test the library:
and that’s it.
Thank you for reading this post. If you like to comment, please do it, feedback will be welcomed.