Sitemap

A Trip to the C Library. Creating Static Libraries

1 min readFeb 28, 2021
Press enter or click to view image in full size
“For whosoever reads this, immense power will bestow them… probably.”

The shallow version:

To compile all your C files in the directory to object files:

gcc -c *.c

To create a library:

ar -rc yourlibraryname.a *.o

Then index your library:

ranlib yourlibraryname.a

The in-depth version:

We use libraries to organize information, which often simplifies access to that information. The same can be said for C libraries, in which a library could house many small functions and scripts, rather than having a huge collection of files in a directory.

Once the library is built, the program main.o can be compiled to an executable with the following command:

cc main.o -L. -lyourlibraryname -o prog

where -L tells the linker to look for the library in the current directory and where -l indicates that this is the name of the library.

But what about the “ranlib” command?

The ranlib command is used to index the library so that symbol look-up is faster in the library. It’s easier to find a book in a shelf when the collection is in alphabetical order. It’s similar with finding code in a collection of scripts.

Finally, please note that libraries are compiled different on mac laptops with M1 chips.

Thomas Francis
Thomas Francis

Written by Thomas Francis

Is currently student at Holberton New Haven