Static Libraries

Lisa Olson
2 min readFeb 12, 2018

--

Libraries are a way of condensing code into smaller units. Instead of having multiple files, we can have one single file that contains multiple object files, all stored at the linking phase. This is what a static library is. We have multiple object code files that we condense into one single executable file that we can use to run the program.

An analogy would be sheet music. Rather than grabbing each page of sheet music right before we need it, we can condense all the pages into one single, ready-to-use binder that we would then grab when needed for showtime (runtime).

Putting together a static library is fairly simple. Using the ‘ar’ command, you can type :

ar -rc libraryname.a file.o file2.o file3.o

ar stands for archiver and it’s the tool used to create static libraries. The r flag tells ar to replace older object files with new ones and the c flag tells ar to create the library if it doesn’t already exist.

From there, we can access and utilize this library in a program by adding the library’s name to the list of object files given to the linker. This is done through adding the l flag to the compiler command, like so :

cc main.o -L. -llibraryname -o program

This command creates a program using the main.o object file and attaches it to the name of the library. -L tells the linker that it may be found in the current directory, hence the ‘.’

Having a library filled with prototypes of functions, set at the linking phase saves time when launching your program, especially when compared to dynamic (shared) libraries. Rather than attaching the dynamic loader to the program, as dynamic libraries do, static libraries allow for the object files to be linked into the program during the linking phase of compilation.

Happy Librarying!

--

--

Lisa Olson
Lisa Olson

Written by Lisa Olson

Front End Developer. Passionate about everything I do. How we spend our days is how we spend our lives.

No responses yet