C static libraries 101
Libraries in C is a set of functions that perform certain tasks. Standard C library is, for instance, linked in a program during the compilation process — when you run “gcc” command. Standard libraries are typically found in /usr/lib directory.
However, not all libraries are linked automatically. If you wish to include libraries other than standard ones (those are included by default while compiling), you must direct linker to which library to search.
Static libraries are included in the execution code. The actual code is extracted by the linker (a copy of the code created) and used to build an executable file. Now the program has everything needed to run successfully. The one disadvantage of static libraries is that if you are to make a change to the source code, you will have to recompile your program to make the changes recognized. All statically linked libraries in Linux have an extension .a .
Building a static library
To create a static library you would need to use a program “ar” (stands for archiver) and put object files ( file.o ) into your static library ( libyourlibrary.a ). Every static library name starts with “lib” and has extension “.a”.
- First of all let’s assemble our .c files, but we wouldn’t link them just yet. That is why we use flag -c.
Command: gcc -c *.c
The output of this command is object files of our source .c files. By default, the object file name for a source file is made by replacing the suffix .c, .i, .s, etc., with .o.
Each source file now has it’s object file.
2. Now let’s create our static library libtaticlibrary.a and put copies of our object files in it.
Command: ar rc libtaticlibrary.a *.o
“ar” — archiver. The “c” flag means that “ar” has to create the library if it doesn't already exist. The “r” flag makes sure to replace older object files in the library, with the new object files.
We just created a static library name “libtaticlibrary.a”.
3. Index your your archive. Compiler will use the index to look up faster for symbols inside the library. It also makes sure that the order of symbols in the library does not matter during the compilation.
Command: ranlib libstaticlibrary.a
How to use static libraries
After you created your library you can use it in your program.
Command: cc files.o -L. -lstaticlibrary.a -o execfile
Where -L. tells linker to look in the current directory for static library -lstaticlibrary.a , link it to the program and pack everything into the executable file execfile.