Create Static Libraries using GCC

Static libraries provide a mechanism by which we can “pack” object code into reusable libraries. In this article I’m going to focus on creating static libraries of C (and C++) objects and functions. Let’s get started.

Creating a static library is actually a very easy process that consists in just two simple steps:

  1. Compiling source code into object code.
  2. Archiving all the generated object code into a single file that represents the library.

Assume we have the following C source files that declare a 3-element vector type and a dot function that calculates the dot product among two vectors:

We can use the following two commands to create a static library:

Please notice we have named our static library “libalgebra.a”. This is not just a random choice as a static library’s name must begin with “lib” and end with “.a” in order to be able to have GCC link new programs against it.

Now that our library is ready, we can redistribute it with the header file “algebra.h” so other programmers can use it in their applications.

In order to illustrate this point further, let’s write a simple C program that includes the header and links against our library:

In the above example you can notice how we can liberally use data types and functions declared in our library as if they where part of this very same program.

Now, in order to compile, all we need is the “algebra.h” header, however, in order to have this program link, we have to use the “-l” (lowercase L) flag of the GCC compiler to specify our shared library, like so:

Given the “-lalgebra” flag, GCC will look for a file called “libalgebra.a” (hence the importance in the library’s naming convention). The “-L” flag tells GCC where this file is located.

One thought on “Create Static Libraries using GCC

  1. Pingback: EUGENE

Comments are closed.