Static libraries in C

Laura Peraltav
2 min readJul 14, 2019

--

Why and how to use them

What is a library?

Basically, a library is a tool that let you decrease the compilation time. They contain several object files (files with the extension .o), that are used as a single one through the linking phase of compilation.

Libraries are usually indexed, feature that facilitates accessibility to symbols (functions, variables, etc.). You must unsderstand that libraries are not executable files, they are just linked to your programs in order for them to run correctly.

Static and Dynamic

There are two types of libraries in C, static and dynamic. In while static libraries are linked in just one step, dynamic are linked in two. Both of them have their advantages.

Static libraries are used by the programs during the compilation process, all of the symbols needed by the program are copied into its file, allowing the program to run by itself without being dependant of the library.

As for the dynamic, the programs just reference the need of the library, this creates a strong dependency on the library, so if the library is not around when the program is running it is not going to perform properly, the real advantage of using dynamic libraries is related to the space saving in memory and that if changes need to be made to the library, the program does not have to be recompiled, because it is linked during run-time based on memory addresses.

In Linux static library extension is “.a” and for dynamic library is “.so”.

How to create a static library?

The basic tool to create a static library is “ar”, that refers to archiver, it is used as follows:

ar rc lib1.a main.o main1.o main2.o

Where “ar” is the command, “r” flag that tells the library to replace any existing files with the new ones and “c” flag creates (in this case) the library lib1.a if does not already exists.

As mentioned before usually libraries are indexed to spped up the search for symbols, some compilers do this automatically, however there is a command that will do that separately in needed:

ranlib lib1.a

This command also updates the library in case an update was made.

To list all files contained in a library use “nm” command:

nm lib1.a

The output will look something like this:

main.o
main1.o
main2.o

To use a library you created just link it to your main.c file when compiling using -L flag, which tells the compiler to look into the current directory along with the standard locations for libraries.

gcc main.c -L lib1.a -o main 

(reference ‘the need to know about C libraries’ by Jennie Z Chu and Static and Dynamic Libraries in Linux by Tu Vo)

--

--

Laura Peraltav

A free soul seeking purpose, willing to learn new things every day. Passionate about photography, digital painting, mindset and entrepreneurship.