C Library Static

Sergio Steben Arias Quintero
2 min readMar 2, 2020

As we are doing computer programs, we realize that some parts of the code are used in many of them. For example, we can have several programs that use complex numbers and the functions of addition, subtraction, etc. are common.

It would be great to be able to put those functions in a separate directory of the specific programs and have them already compiled, so that we can use them whenever we want. The huge advantages of this are:

Not having to rewrite the code (or copy-paste).
We will save the time to compile each time that code that is already compiled. In addition, we already know that while doing a program, we test and correct, we have to compile between many and “more many” times.
The code already compiled will be tested and reliable.
The way to do this is to make libraries. A library is one or more functions that we have already compiled and prepared to be used in any program we do.

To build a static library we must perform the following steps:

  1. Obtain the object files (.o) from all our sources (.c).
    For this they are compiled with gcc -c source.c -o source.o. The -c option tells the compiler not to create an executable, but an object file.
  2. Create the library (.a).
    To do this, the ar command is used with the following parameters: ar -rv libname.a source1.o source2.o … (etc.) (if you want to insert all the object type files you can use the wildcard * .and thus avoid indicating file by file)
    The -r option tells the ar command that you have to insert (or replace if they are already inside) the object files in the library. The -v option is “verbose”, so that it shows information while it is doing things to be used in any program we do

--

--