C static libraries

Yoyman Manuel Castellar Miranda
3 min readMar 2, 2020

It is known as libraries (or libraries) to certain types of files that we can import or include in our program. These files contain the specifications of different features already built and usable that we can add to our program, such as reading from the keyboard or displaying something on the screen among many others.

Why use libraries?

Libraries contain the object code of many programs that allow you to do common things, read the keyboard, write on the screen, handle numbers, perform mathematical functions, etc.

Libraries are classified by the type of work they do, there are input and output libraries, math, memory management, text management and as we imagine there are many libraries available and all with a specific function.

How they work?

Using a static library means only one object file need be pulled in during the linking phase. This contrasts having the compiler pull in multiple object files (one for each function etc) during linking. The benefit of using a static library is that the functions and other symbols loaded into it are indexed. This means instead of having to look for each entity on separate parts of the disk, the program need only reference a single single archived object (.a) file that has ordered the entities together. As a consequence of having one ordered object file, the program linking this library can load much faster.

How to create them?

  1. Create a C file that contains functions in your library.

/* Filename: lib_mylib.c */
#include <stdio.h>
void fun(void)
{
printf(“fun() called from a static library”);
}

We have created only one file for simplicity. We can also create multiple files in a library.

2. Create a header file for the library

/* Filename: lib_mylib.h */
void fun(void);

3. Compile library files.

gcc -c lib_mylib.c -o lib_mylib.o

4. Create static library. This step is to bundle multiple object files in one static library (see ar for details). The output of this step is static library.

ar rcs lib_mylib.a lib_mylib.o

5. Now our static library is ready to use. At this point we could just copy lib_mylib.a somewhere else to use it. For demo purposes, let us keep the library in the current directory.

How to use them?

1. Create a C file with main function

/* filename: driver.c */
#include “lib_mylib.h”
void main()
{
fun();
}

2. Compile the driver program.

gcc -c driver.c -o driver.o

3. Link the compiled driver program to the static library. Note that -L. is used to tell that the static library is in current folder (See this for details of -L and -l options).

gcc -o driver driver.o -L. -l_mylib

4. Run the driver program

./driver 
fun() called from a static library

--

--