C Static Libraries

Daniel Celis Tobon
2 min readJul 15, 2019

--

What is a C library?

A library is a file that contains other files and functions that we can call and reuse from our program without having to create them again. An example of this is the library <stdio.h> (standard library) in which we can find the function ‘printf’, which is what we use when we want to print something on the screen.

To create our own library we must do the following:

First we gather all the files that we are going to add to the library.

$ ls * .c0-isupper.c 
1-isdigit.c
2-strchr.c
3-islower.c
4-isalpha.c

Then we create the object files for each source file, which will have the extension ‘.o’, this we do when we compile by adding the flag ‘-c’.

$ gcc -Wall -pedantic -Werror -Wextra -c * .c

Then we create the library “lib.a” using ‘ar’ or ‘archiver’ and add a copy of the object files.

$ ar –rc lib.a *.o

After having added the files to the library we must index them. The command used to create or update the index is called ‘ranlib’.

$ ranlib lib.a

If we want to observe that the necessary files were left inside the library, we use the following command:

$ ar –t lib.a 0-isupper.o
1-isdigit.o
2-strchr.o
3-islower.o
4-isalpha.o

We can also see the contents of the object files with the following command:

$ nm lib.a 0-isupper.o:
0000000000000000 T _isupper
1-isdigit.o:
0000000000000000 T _isdigit
2-strchr.o:
0000000000000000 T _strchr
3-islower.o:
0000000000000000 T _islower
4-isalpha.o:
0000000000000000 T _isalpha

--

--