Static Libraries in the C Language

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.

To view or add a comment, sign in

More articles by Alex Allen

  • The Internet of Things

    IoT Defined The Internet of Things, ubiquitously abbreviated as IoT, refers to the connection of different types of…

    1 Comment
  • ls -l in the shell

    For the past two weeks, my partner Afa and I have been writing, testing, and documenting our own linux shell. This is…

Explore content categories