Static Libraries in C

Static Libraries in C

Table of contents

Static libraries are hard, but that's no reason we shouldn't understand it. The last step during compilation is the linker. The linker links the object codes to make an executable. Of course, one can gather several object files and share them. These files can be used as libraries that can be linked with other source codes either at compile time or at runtime. When linked at compile time, they are usually called static libraries.

Static Libraries.

Static libraries are typically object files stored and linked with the program during compilation. Creating a static library is simply creating a collection or an archive of these object files in one file. The ar (archiving) is used to make an archive from these object files. To create one, the ar command is used to make an archive from existing object files. Static libraries usually use an extension of '.a' in Linux and this is usually done when creating the library.

The command archives files 3-islower.o, 3-puts.o and 3-strcmp.o in the triallib.a library (or file). After creating the library, the 'ranlib' command is used to generate an index to the archive file ( to the library). This will give your library functions an index that the compiler can look up when using it. The 'nm' ( with the -s or --print-armap options) command is used to show these indices in the archive (static library).

When creating the library using the ar command, the -s option is used to add an index to the generated library. i.e.

Creating an index is usually advisable as it eases the compilation process.

To link your library(custom static library), not the standard library, while compiling use the '-l' flag along with the library ( using the gcc compiler in Linux).