C static libraries

Daniel Ortega Chaux
2 min readMar 1, 2021

A library is where we can keep items that we might call later for our program, which will actually save us a lot of time.

But what is a static library in C?

Is a compiled file which contains the symbols that the main program needs to operate, such as functions and variables.

When we call a function in the main, the compiler will link that code wrote in main with the code of the function that is in the library, and it will be added.

Theres another type of library in C called dynamic library:

The process of compilation is still the same of the static libraries until it gets to the linker, add that point it will be added not the code of the function you called but the address where the function is located in the library.

But why should we use them?

Libraries provide you with many useful functions that will save you time by using them instead of waste time trying to create them.

How to create a static library in Unix? How it works?

  1. Compile and assembly your .c file with the command: “gcc -c *.c” (with the “-c” flag we make sure it compiles and assemble but not link) and will create the “.o” extension file which mean object code.

Example:

Example_file.c Hello_world.c

gcc -c *.c

ls

Example_file.c Example_file.o Hello_world.c Hello_world.o

2. Then we use the command “ar” which means archiver to create a static library adding an “rc” which stands for “replace” older objects with the new one and “create” library if it doesnt exist.

Example:

ar rc Example_library.a Example_file.o Hello_world.o

or

ar rc Example_library.a *.o

This command creates a static library called Example_library.a and puts copies of the object files Example_file.o, Hello_world.o in it. As you can see in the last line we used the “*.o” command which means it will copy all the files ending with “.o”.

But how do we use libraries?

After we create (modified) them, we just need to index it by the “ranlib” command.

Example:

ranlib Example_library.a

--

--