A brief introduction to C static libraries

Wiston Venera Macías
2 min readOct 12, 2020

--

To start talking about C static libraries we need to know what is a library and when is necessary to use one. A library is a place where you can find a collection of books and we use a book when we need to check a piece of information for a specific use. C libraries work in the same way, but instead of books, we have functions. We can incorporate a lot of functions into our code just by using the right library. E.g. to print whatever we want, we need to incorporate the standard input-output library stdio.h to have access to the printf function. When we are programming we need to reuse functions, but copy/paste those codes into the current one could make our current code unreadable. Instead, we can create a library with all the code we’ve written so we can access every function without the need to rewrite it.

The static libraries are loaded in the final phase, linking, of the compilation process.

Lets got to create a static library with our own functions. First, we need to copy all the .c files, we want to include in our library, to a new folder… Yeah, I know we can omit this step but write the path to every file is more complicated than copy the file to a new folder. Now we need to create a new header file “.h” with the prototype of every function that is in the code we copied.

Now we need to run the gcc command with the flag -c to every file in our folder gcc -c *.c (imagine be writing the path to every file here…) with this flag we are creating .o files (machine-level instruction files)

Click on the link to know about GNU Compiler Colection — GCC

With the next command, we’re going to create a single file that will contain all the .o files created in the previous step. Is like zipping. The command is ar -rc “thenameyouwant”.a (without the quotation marks). And that’s all.

More about the ar command here

If we want to use our new brand library only we need to reference our header file into our code and include the .o file when we’re compiling e.g. If the name of the header file is mylibrary.h and the name of the library is mylib.o, we reference the header file into our code with #include “mylibrary.h” (with the quotation marks this time) and when we’re going to compile just reference the .o file gcc myapp.c mylibrary.o (remember to copy the .h and .o files to the same location as your main code).

With the static libraries, we can maintain our code organized and clean, also we can share our libraries without sharing the code (maybe the code is a mess but it works!).

--

--