Keep It DRY With Static Libraries
One of the fundamental maxims of computer programming is DRY, or Don’t Repeat Yourself. A typical application of this principle occurs when you find yourself writing a function that is very similar to another function already in your code, but a little different. Instead of copy and pasting and making minor modifications, you are much better off finding a way to create a more broadly applicable function that can satisfy both uses, and possibly, other purposes down the line.
Moving from interpreted programming languages to compiled languages, it is necesssary to learn new engineering skills to create reusable software components. One of these skills is the creation of static libraries.
What is a Static Library?
A static library is a set of object files compiled into a single file. Which leads to an obvious next question: What is an object file? Simple answer: An object file is machine code that is almost ready to be integrated inot an executable file. To create object code, we can pass the
-c flag to the C compiler like so:
gcc -c very_useful.c . This creates object code with the following format:
very_useful.o . You can put a group of useful object files into a Static Library, thus making them available for future use. DRY, remember?
Advantages of Static Libraries
Static libraries have a lot going for them. These advantages include
- Ensuring that your program can call the correct versions of the program’s dependencies. This is not possible when depending on dynamic libraries, which are generally available system wide. See dependency hell.
- Linking your code to a static library creates a single executable. This makes your executable file more portable.
- When you compile your code using a static library, only the parts of the library that your code references are included in the created binary — no bloat!
How to Create A Static Library
Starting with a set of object files, issue a command like so:
ar rc libkool.a bill.o ted.o adventure.o
In the above example the archiver program takes the object files
adventure.o and puts them into the static library
libkool.a. Next, the archive will need to be indexed. This done with the
ranlib program like so:
Use Your Static Library Powers for Great Good:
In the land of linux, we say this when we want to compile a program that utilizes a static library:
gcc example.c -lkool
lkool causes the compiler to utilized the
libkool.a static library. Assuming that you write code that compiles correctly the first time (like I do) the above command will create an executable file
a.out . Whammo blammo.