C static libraries.

Esneider Granada Valencia
2 min readMar 1, 2021

The C libraries come’s to manage very larger projects where the code becomes too entangled, therefore, if we are working with projects that need several pieces of code that not change trough time (functions) then we can approach the potencial of libraries, making that our functions doesn’t pass by compilation each time.

A library in C language is a file that contains several object files, and this file can be used as a single entity in a linking phase of a program. Since the libraries are indexed, it’s easy to find functions, variables, etc.

Create a static library

To create a library we can use the command ‘ar’, with this command we can create a static library, modify object files in the static libraries and list the names of object files in the library.

The follow scrip creates a library that will contain one object file.

ar -rc libmylib.a file.o

This command creates a static library named ‘libmylib.a’ and puts the copie of the object file ‘file.o’. If the library file already exists, it has the object files added to it, or replaced, if they are newer than those inside the library. The 'c' flag tells ‘ar’ to create the library if it doesn't already exist. The 'r' flag tells it to replace older object files in the library, with the new object files.

Using a C library

After we created our archive, we want to use it in a program. This is done by adding the library’s name to the list of object file names given to the linker, using a special flag, normally '-l'. Here is an example:

gcc file.o -L. -lmylib -o file

This will create a program using object file “file.o”, and any symbols it requires from the “mylib” static library.

Note that the usage of the '-L' flag - this flag tells the linker that libraries might be found in the given directory ('.', refering to the current directory), in addition to the standard locations where the compiler looks for system libraries.

--

--