Static libraries in C language

Paola Andrea Garcia Altamirano
2 min readJul 14, 2021

By Paola Andrea García Altamirano.

Also called object-libraries, they are collections of (compiled) object files grouped into a single file with the extension .lib, .a, etc. together with one or more header files (generally .h).

Static libraries are .a file, All code related to the library is in this file, and it is directly linked to the program at compile time. A program that uses a static library takes copies of the code it uses from the static library and makes it part of the program.

How to compile static libraries in C language

Once we have our code, to get a static library we must perform the following steps:

  • Get the object files (.o) from all our sources (.c). For this they are compiled with cc -c source.c -o source.o. The -c option tells the compiler not to create an executable, but just an object file. Here I put the cc compiler, because it is the one I used for the example, but you can use GCC, or the g ++ (for C ++) or one of Fortran, Pascal, etc.
  • Create the library (.a). To do this, the ar command is used with the following parameters: ar -rv libname.a source1.o source2.o … The -r option tells the ar command that it has to insert (or replace if they are already inside) the files object in the library. The -v option is “verbose”, so it displays information while you’re doing things. Next, we put all the object files that we want. ar is actually a much more generic command than all this and can be used to pack any type of file (not just object files). It also has options to see what files are inside, delete some of them, replace them, etc.