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:

/** algebra.h **/

#ifndef ALGEBRA_H
#define ALGEBRA_H

typedef struct
{
	float x, y, z;
} Vec3;

void vec3Init(Vec3* v, float x, float y, float z);

float dot(Vec3* a, Vec3* b);

#endif //ALGEBRA_H
/** algebra.c **/

#include "algebra.h"

void vec3Init(Vec3* v, float x, float y, float z)
{
	v->x = x;
	v->y = y;
	v->z = z;
}

float dot(Vec3* a, Vec3* b)
{
	return a->x * b->x + a->y * b->y + a->z * b->z;
}

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

gcc -static -c algebra.c -o algebra.o
ar -rcs libalgebra.a algebra.o

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:

#include <stdio.h> /* printf */
#include "algebra.h" /* our library's header */

int main()
{
	Vec3 a;
	Vec3 b;
	vec3Init(&a, 1.0f, 2.0f, 3.0f);
	vec3Init(&b, 3.0f, 2.0f, 1.0f);
	printf("<a,b> = %.2fn", dot(&a,&b));
}

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:

gcc main.c -L. -lalgebra
$ ./a.out
<a,b> = 10.00

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.