Static Libraries in C

Alexis Coronado
3 min readMar 8, 2021

What is library static?

In the C programming language, static libraries are simply a collection of ordinary object files; conventionally, static libraries end with the suffix “. to “. This collection is created using the ar (archive) program.

Static libraries allow users to link to programs without having to recompile their code, saving compilation time. Static libraries are often useful for developers if they want to allow programmers to link to their library, but don’t want to give the library source code (which is an advantage for the library provider, but obviously not an advantage for the programmer trying to use the library).

How to create a static library?

To create a static library, we need to specify to the compiler, which is GCC in our case, we want to compile all the code in the library (* .c) into object files (* .o).

gcc -c *.c

To create a static library or to add additional object files to an existing static library, we have to use the GNU ar (archiver) program. We can use a command like this:

ar -rc libholberton.a *.o

This command creates a static library named “libholberton.a” and puts copies of the object files. The ‘c’ flag tells ar to create the library if it doesn’t already exist. The ‘r’ flag tells it to insert object files or replace existing object files in the library, with the new object files.

Now, we use the ranlib command to generate an index of the contents of a file and store it in the file. The index lists each symbol defined by a member of a file that is a relocatable object file.

ranlib libholberton.a

If we want to see the contents of our library, we can use the ar option -t.

ar -t libholberton.a

Once you’ve created a static library, you’ll want to use it. You can use a static library by invoking it as part of the compilation and linking process when creating a program executable. If you’re using gcc to generate your executable.

How to use?

Now we can use the command below to create our final executable program:

gcc main.c -L. -lholberton -o quote

Flags description:

-L : Specifies the path to the given libraries (‘.’ referring to the current directory)

-l : Specifies the library name without the “lib” prefix and the “.a” suffix, because the linker attaches these parts back to the name of the library to create a name of a file to look for.

That would be the whole process.

--

--