Static Libraries : What use ?

What are Static Libraries ?

It’s a collection of object files that can be used to link to programs without recompiling it’s source corde. It is less used that it was, as the compilation are faster nowadays and the main goal of a static library is saving recompilation time. But it still can be useful, for example when a programmer want to gave others the permission to link to the library but not the source code itself.

The other type of libraries is shared library, also called dynamic libraries, that can be shared by multiple executable files, rather than being copied by a linker, it is loaded from individual shared object.

Libraries in general are very useful to built programs, as you can call functions rather than implement them everytime. It improves the ergonomy and it saves time that can be considerable depending of the program.

But how to make them ?

To built them, you will need to use the ar command that is used to create and modify archives, to know more about it, I invite you to search the manual page of ar. In order to create the static library, we need to use ar with options like r (insert the targeted files into the archive), c (create the archive) and s (index the object-files into the archive), you can see more about them in the manual page as well.

Here an example of how we can do it :

ar rcs our_library.a *.o

We are calling the library “our_library.a”, know that the extension is different depdending of your operating system, .a will be for linux and Mac but for Windows it will be .LIB. For dynamic libraries it will be .so for Linux and Mac, and .DLL for Windows.

Next we insert all our files that finish with the extension .o, and finally the s option will built the index of our library. Now I imagine that you want to use it so this step is quite simple, to illustrate it I will use GCC.

You can use it by calling it in the compilation command, in GCC the option to specify a library is -L, place it after the name of the file that you want to compile as it’s a linker option.

Here an example of how we can use it :

gcc source.c -L. -our_library -o our_file

It will search in directory for the specified library file, and will compile the “source.c” file using our library to create “our_file”.

I hope that helped you to understand more about static libraries, thanks for your reading !

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store