C — Static Libraries

Carson Stearn
2 min readFeb 28, 2021

What are Static Libraries in C and how do they work?

Most programs are made up of functions. Functions serve as mini-programs within the program itself. They can be used by the main program to perform specific actions to help accomplish its task. In order for the program to know how to use these functions it must know how they work. This is where the static library comes into play.

A static library is like a reference to a collection of books. Each of the books contains the code to show how a function works. They can be read and used by any program that has access to the library.

Why use static libraries?

Static libraries help keep programs organized and reduce it’s overall size. They also help make it more human readable. In addition, you can save a lot of time and potential debugging by reusing someone else’s function for your program. A static library will provide a refence to the functions needed by your program and can be called upon when required.

How to create a static library?

The first step to making a static library is to compile your .c files into object files. You can do this for all current files in the current directory with the following:

gcc -c *.c

Now you will use all the .o files and create a new library using the ar command and name the file newlib1:

ar -rc newlib1.a *.o

Sometimes you will need to index the library which can be done with the ranlib command:

ranlib newlib1.a

After all that, it’s best to check the contents of the library to make sure everything you wanted ended up inside. This can be done like this:

ar -t newlib1.a

You can also see the symbols in the library using the nm command:

nm newlib1.a

How to use the newly created library?

You’ve now created a new static library and want to use it. When compiling your program you can use the -L function without the extension to allow the library to be used as a reference. Using main.c file as an example:

gcc main.c -L -newlib1 -o main

This will convert your .c file using the functions it needs by referencing the library and create an executable file called main which you can run with:

./main

In conclusion, static libraries are a very useful tool when creating more complex programs. Allowing you to focus on creating the code you want by using already created functions to expedite the process can be very beneficial. Not only does it save time but it also helps make the code human readable and more concise in it’s operation.

--

--