C static libraries - significance and usage.
A static library is a file that consists of a collection of object files (*.o) that are linked into the program during the combing phase of compilation and are not pertinent during runtime.
A computer file that contains an object code is an object file, that is a machine code output of an assembler or compiler. To create it we have to add flag ‘c’ to the compilation code of our .c file, this compiles source files without linking.
Why do we use libraries? How do they work?
In the library we can include files from our programs that contains functions we may want to use in another program.
Without the library, we would have to declare and define each function we are going to use. But, since the functions are already incorporated in the files of our library, we will only need to add the library to our program.
To do this, we should write in the beginning of the file: #include <library_name.a>
How to create static libraries?
As I said before, we have to compile using the ‘c’ flag in all the files that we would like to include in our library.
$ gcc -c -Wall -Werror -Wextra *.c
Once we have object file(s), we can now insert all object files into one static library.
A program called ‘ar’, (for 'archiver') is what we use to create a static library, which are actually archive files. It is also used to modify object files, list the names of object files, etc.
To create the library we use the following command:
$ ar -rc libname.a *.o
‘libname.a’ is the name of static library created by this command and this puts copies of all the files with the .o extension (object files).
The ‘c’ flag instructs ‘ar’ to set up the library if it doesn’t already exist. And the ‘r’ flag tells it to reinstate older object files in the library, with the new object files.
After an archive is created, it should be indexed, which can be done with the subsequent command:
$ ranlib libname.a
Your library is now ready to use! The only thing left,as I explained earlier, is to include it to our program.