C Static Libraries
Trinity College, Dublin Library

C Static Libraries

What are Static Libraries and Why are they needed?

A Static library is a set of routines (external functions, variables, classes, etc) which are resolved in a caller at compile time and copied into a target application (your program) producing an object file and a stand-alone executable. The executable and the process of compiling it are both known as static build of the program, hence, static library.

No alt text provided for this image

What does this all mean? It simply means we are reusing code that was already written and optimized somewhere else and therefore saving ourselves time by not having to do everything from scratch.

How to Create a Static Library in C

To create a static library in c we first need to compile all our .c files into object files and make sure there aren't any errors in our .c files.

$ gcc -Wall -pedantic -Werror -Wextra -c *.c        

Next, let's create and archive our library using these object files:

$ ar -rc libname.a *.o        

What do these flags do? The -r flag will replace all old object files with the newly compiled ones, while the -c flag will create the archive.

Next up, we need to index our library. This will make a header in our library with the symbols of object files. This is later used by the compiler to speed up symbol-lookup. This can be done by running the following command:

$ ranlib libname.a        

This can also be done directly with the ar command when creating the archive by adding the -s flag:

$ ar -rcs libname.a *.o        

To confirm which object files are in our newly made library we can run the -t flag, like so:

$ ar -t libname.a        

How to Use a Static Library?

Now that we have created our library, let's use it in our programs.

To do this, we will be invoking our library during the compilation/linking process of our main.c program:

$ gcc main.c -L. -lname -o main        

Let's go over these flags:

-L.: This flag specifies the path to the library, which in this case is in the same directory, hence the '.'. If the library is located in a different directory, then we would have to indicate it's path. Ex: -L/home/tmp

-l: With this flag we need to attach the library name but without the lib- prefix and the -.a extension.

Now you are ready to run your executable!

./end

To view or add a comment, sign in

Explore content categories