How to create static libraries with gcc?

gccStatic library or statically-linked library is a set of routines, external functions and variables which are resolved in a caller at compile-time and copied into a target application by a compiler, linker, or binder, producing an object file and a stand-alone executable. Here I will try to explain how to create a static library with gcc.

Code for the library:

First we write some code for our library. The below function will find and return the factorial of a number.


fact (int f) {
  if ( f >= 1 )
    return f;
  return f * fact ( f - 1 );

We need to create a header file to define our function.

int fact (int);

Creating static library:

Static libraries are simply a collection of ordinary object files; conventionally, static libraries end with the ‘.a’‘ .
To generate object file use ‘-c‘ flag with gcc.

$ gcc -c fact.c -o fact.o

-c Compile or assemble the source files, but do not link. The compiler output is object files corresponding to each source file.
-o To specifiy the output file name.

A static library can contain more than one object files. We need to copy all object file in to a single file. This single file is our static library. We can use archiver(ar) to create to create our static library.

$ ar rcs libfact.a fact.o


r – Insert the files into archive (with replacement).
c – Create the archive.
s – Write an object-file index into the archive, or update an existing one, even if no other change is made to the archive.

Note: the library must start with the three letters lib and have the suffix .a.

A program using the library:


#include <stdio.h>
#include "fact.h"
main(int argc, char *argv[])
        printf("%d\n", fact(4));
        return 0;

Linking our static library:

$ gcc -static main.c -L. -lfact -o fact


-L Add directory to the list of directories to be searched for -l.

Now run program:
$ ./fact