C — STATIC LIBRARIES

Luis Angel Vargas Mosquera
2 min readMar 3, 2020

--

Each function from the standard libraries put on the header of the file with the “.h” file, has the compiled file of that function on a file “.a”, that has the description and the files of each function and your uses. Samely, each of our self functions needs a file that describes and has compiled our files of functions and prototypes, and that is we call libraries.

Why use libraries?

When you create a program in C, and you are using the standard libraries from Linux, really you are calling the function from a file on the /usr/lib (or /usr/lib64 on a 64 bits system) directory. If you need to use your self functions by the program runs, the best idea is to compile that on a static library, and each time you call your functions the system will know where to look for, avoiding that the program crashes or finish or give us results that we don’t expect.

How they work?

On a static library, we save all the files type “object” (ended in “.o”) on just one file (ended in “.a”) from files “.c” that contains the function. If we call some function, our system looks for first on the static libraries, simplifying the tasks to do and keeping memory free.

How to create them

When we have the object files (“.o”) using the GCC compiler with the flag -c of each function file to use, just we use the command “ar” with the next syntax:

ar [OPTIONS] archive_name member_files

Remember that this command only receives objects files “.o” created by the “gcc -c” command.

Once this process finishes we need to use the command “ranlib” to add or update the object file on the static library.

ranlib librarie_name

How to use them

We need follow 3 steps to use the libraries in C:

  1. Write the header file on the top of the main program.
  2. Use the functions and variables on this library as you need.
  3. The library is linked together with the executable program.

--

--