Static Libraries in C: what are they?

Static Libraries in C: what are they?

C static library is composed of compiled object files (.o) that contains functions, variables, and other symbols required by the main program to operate. Static libraries are created in the linking phase of compilation, where object files for each function in a program are all pulled in into a archived object file (.a). Functions that are loaded into the static library are indexed, thus causing the program linking to this library to load much faster. Static libraries are an exceptional tool that not only speeds up program loading, they provide fewer resource use and reduce the amount of size of memory a program could take up. Below are the steps for creating a static library.


#HOW CAN I CREATE A STATIC LIBRARY?(in 3 easy steps!)

1. Step 1:

Have all relevant .c files and header files in a local directory. Make sure all files and functions are complete and header files are defined as well.

No alt text provided for this image

2.Step 2:

Compile all .c files by using the gcc option to stop at the linking phase of compilation, “-c”. The compiler will create a copy .o file for each source file.

No alt text provided for this image

3. Step 3:

Once we have all the necessary object files the next step is too archive them and make a static library. We use the command ar to perform that tasks. Below we use the command to create a library called “liball.a”.

No alt text provided for this image


How can we use static libraries?

Now that we have out library completed, we can use it with other programs. In order to use the created static library we need to include it in the gcc compiling code, using the indicators l(library name) and -L(path to library) like the example below.


No alt text provided for this image


Once compiled we can run the executable ./main which invokes the library. Thanks to static libraries we can keep a collection of functions that can be easily accessed and speed up the process of programs.



To view or add a comment, sign in

More articles by Fernando Aponte

Insights from the community

Others also viewed

Explore topics