Static libraries in C

Carlos Galeano
3 min readFeb 27, 2021

First of all, let’s talk about what a C static library is; basically, a static library or statically-linked library is a set of external functions compiled which contains all the variables that are required to run programs. For instance, stdio.h is a static library which we normally use in our programs but don’t really pay much attention to it whilst we are constantly using it. Here’s a few of these functions printf(), puts(), scanf(). Once a file is compiled the compiler creates object code. Right after the code was created, it’s also linked. The main purpose of the linking process is to make the functions available for your programs so that they can be used and called later on.

Quite simple… Right?

I know… Just ignore Bojack’s expression. Now that you know what it is, let’s take a closer look of how you create them, shall we? I know, you gotta be hella excited at this point, aren’t you!?

· First thing firts, let’s create the .c file on which you will have your fancy function on, something like this:

· Now you have to create or edit your header life and add the prototype as in, your function name and variables.

· Now compile your library files using the following command:

gcc -c *.c

· (please notice it will compile all the files ending with the extension .c) as we believe it’ll be better to save time) but if you do NOT want that, you can use this command instead:

gcc — yourSource.c -o yourExecutable.o

· Now, let’s create the static library, in this step we will be bundling multiple object files in our lovely library so that we can get the static library as output. Use the following command so that you will be bundling all your files with the extension .o:

ar -rc yourlibname.a *.o

· You’re all set now and you could run your program if you wish by calling your executable and your function name as shown below:

./executableFile functionName()

--

--