C Static Libraries: how do they work?
A static library, also known as a statically-linked list, is simply a common space used to store object files. Once created they allow the user to be able to link programs with each other without requiring recompilation. They also allow 3rd party linking without having to give out the library source code. A purported plus is a slight increase in overall speed as the compilation skipped sheds a bit of processing load, this however is negligible with today’s faster compilers and is more of a footnote of why they were used in the past.
Static libraries work by indexing the object files that are passed to it. In simple terms it neatly stores all the .o files that are passed to it. This way, upon the linking stage of compilation, our compiler doesn’t have to scramble around searching for the necessary functions in memory, instead they are all stored in a single .a file and are readily accessible at runtime. It is not necessary to name your static library files with a .a extension, but programmers enjoy their conventions and will look at you funny if you stray from the path.
To create a static library
We must first ensure that we have our functions properly created in their own .c files. Once we’re sure we have everything we need we can move on to compiling. A simple
$ gcc -c <filename.c>
command will compile our file into an object file output. Now it’s ready to be added to a library! We call upon our archiver with the command:
$ ar -rc <libraryname.a> <filename.o>
A final step is to ensure that our files are properly indexed after being added to our library is by running:
$ ranlib <libraryname.a>
And just like that we have created and sorted our library file to ensure the quickest compilation times!