Static Libraries in the C Language
Why use libraries
We use libraries to add predefined functions to our own programs. This saves the programmer time by eliminating the need to write common functions from scratch. Functions from static libraries are effectively copied and pasted into our own programs at compile time, during the linking phase of the compilation process.
How libraries work
A static library is a collection of object files in one library file. When the linker is about to generate our executable file, it resolves the reference symbols for the function definitions needed (ideally facilitated by an index of defined symbols). The linker links the object code for the library functions to our executable program.
How to create libraries
To create a static library for the C language we use the “ar” archiver program. We create a “.a” archive file and then add “.o” object files to the library. Then we index the contents of the library with the “randlib” command. The index will be used by the compiler to speed up symbol-lookup inside the library.
How to use libraries
Once we’re ready to use a library in a program, we need to add the library’s name to the list of object files given to the linker. For instance, if we need to compile a culpepper.c program that is dependent upon our static library of libcongress.a we need to call our compiler in a particular. Instead of the typical “gcc culpepper.c” command line call, we will call “gcc culpepper.c -L. -lcongress” to include the library. Notice that we replace the “lib” in libcongress.a with just the “-l” library flag and we remove the extension “.a”. The “-L.” flag tells the compiler to look in the current directory for our library.