Andrew Kalil Ortiz
2 min readFeb 29, 2020

Static Libraries; why use them and how they work.

static libraries

What is a library and why do we use it?
In general, a library in C programming is used to hold functions that can be used when writing a code. These functions can be “called” when writing a code in a main function to perform task that only those functions can perform. A static library is a file that contains functions, variables and routines which are resolved in a “caller” during compile time as well as copied into the destination application by a compiler. This produces an object file and a stand alone executable. We use libraries in order to hold function for us. This therefore allows us to only use the function in our application code without having to write the function and declare it outside of the main function. It is similar to using the <stdlib.h> or <stdio.h>; where we simply use functions such as ‘printf’ and ‘putchar’ without having to first write the code for the function. However this causes the program to have more weight because there are functions being added at compilation time. This is because called functions are copied into the program instead of referenced.

How does the static library work?
Basically, the static library contains all compiled files with .o extension which contain functions. When used for linking, the linker will search for .o files in the library that ware declared in the main program and pulls those .o files. This will prevent having to write function in the program.

How to create a static library?
1. Ensure that all of the source file with .c extension containing the functions are present in the directory that you will be working in.
2. compile all of the source files that you want to add to the static library with the following command:

$ gcc -c *.c

3. Create the static library and add all of the functions you want in it with the following command:

$ ar -rc libname.a *.o

4. If you want to check the content of the library, the following command can be used:

$ ar -t libname.a 

How to use a static library?
Use a static library by first linking it and compiling it along with the executable program. This way you do not have to declare and create the function in your program. The command for this is:

$ gcc my_program.c -L. -lnameoflibrary -o function_name

The process looks something like this:

Andrew Kalil Ortiz
Andrew Kalil Ortiz

Written by Andrew Kalil Ortiz

Life has a valuable lesson every day.

No responses yet