Creating and Using Static Libraries in the C Programming Language

Adam Taylor
2 min readMar 1, 2021

A static library is a file that contains .o object files inside of it that can all be used at once while linking to a program. When compiling a file, the system will go looking for different functions and variables, and using a static library allows the system to find almost everything it needs in one place, saving time. If you know anything about C, it is all about saving time and memory.

Creating a Static Library

The command to create a static library is “ar”, which means “archiver.” This command is capable of creating libraries, listing the names of object files in the library, and modifying .o files as well. Once created, your libraries extension will be .a, meaning it is a file that contains other files. To create object files, you can use the compiler gcc, for example.

ar rc libholberton.a *.ogcc -c *.c

In that first line of code, you are creating a library named “holberton.” Now, you must know that in order to create your own library, you have to use “lib” in front of your desired library name. In “rc”, the “r” flag ensures that older files will be updated by being replaced with new .o files. The “c” flag is what creates the library if it has not already been made at this point. Not to mention that “*.o” is a wildcard that includes all files ending in “.o” in the static library. In that second line, we are compiling all of our .c files with the wildcard “*.c”. The “-c” flag compiles your sources to object code (input to linker).

Using Static Libraries

The reason we use static libraries is to use what is inside of said libraries with different programs. If your library is located in a standard directory, then you can use code like this to compile it.

gcc test_code.c -lholberton -o test_code

In that code, the “-l” flag before “holberton” tells the compiler to look for an archive called libholberton.a. As mentioned before, the format for library names always has to include “lib” before your desired name of the library itself, as that is what the compiler looks for. Now, if you were to run the above code with a program that has functionality, you would net yourself a new executable file with the same name. Now, all you would have to do to actually run your new executable file is put “./” preceding the file’s name in your terminal, and it will execute your code.

I hope this helped you understand how to create static libraries and their functionality. Good luck out there! ╰(*°▽°*)╯

--

--