C static libraries

Why use libraries?
Using libraries will speed up the linking stage of compilation since there’s less files to look for and open.

What is a static library?
A static library is a collection of object files that can contain functions, variables, etc. In Linux static libraries end with the ‘.a’ extension and Microsoft Windows uses the “.lib” extension.

How to create them

Lets say we wanted to create a static library with two functions, “strlen.c” and “atoi.c”. First get the object files from the source code.

-$ ls
atoi.c header.h main.c strlen.c
-$ gcc -c strlen.c atoi.c
-$ ls
atoi.c atoi.o header.h main.c strlen.c strlen.o

Now that the object files are created use the archiver (ar) to create a static library.

-$ ar -rc libf.a strlen.o atoi.o
-S ls
atoi.c atoi.o header.h libf.a main.c strlen.c strlen.o

This creates a static library named libf.a with both object files copied inside. The ‘c’ flag creates the archive and ‘r’ is used to replace older object files with newer files. Now we must index the library with ranlib so that the compiler can speed up symbolic lookup inside the library. You can list the symbols from libf.a by using ‘nm’.

-$ ranlib libf.a
-$ nm libf.a
strlen.o:
0000000000000000 T _strlen
atoi.o:
0000000000000000 T _atoi

How to use them

The main.c file uses the functions in libf.a to get the length of string “Hello, World” and the integers from the string “num 123”. This command tells gcc to use main.c with our library ‘-lf’ to create a program named ‘exe’ . The ‘L’ flag will look for libraries from a given directory.

-$ gcc main.c -L. -lf -o exe
-$ ./exe
Length: 13
Int: 123
Like what you read? Give Jared Heck a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.