CRASH COURSE: These libraries are sure to make your hair stand up!

What is a Static Library?

This is a library where modules are bound into the executable file before execution. It is a collection of object files which are linked into a program during the last phase of compilation (linking phase).

These libraries are commonly named libname.a. As it is known, static libraries end with the ‘.a’ suffix. This suffix refers to archive. Though they aren’t used as often as they once were, they are still sometimes used and relatively simple to explain.

Why use Libraries?

A great perk of using these nifty libraries is execution speed at run-time. Because the binary code is already included in the executable file, multiple calls to functions can be handled very quickly and efficiently.

How they work:

The libraries’ collection of .o files are put together in an archive. When linking, the linker searches the library for .o files that provide any of the missing symbols in the main program, and pull in those .o files for linking, as if they had been included on the command line like .o files in your main program. The process is applied recursively! Recently, at Holberton School, we have been learning about recursion so it is interesting to see it in action in another manner.

If any of the .o files pulled from the library have unresolved symbols, the library is searched again for more.o files that provide the definitions.

How to create them?

First, make sure to compile all existing .c files.

gcc -c *.c

To create a static library, or to add additional object files to an existing static library, we use a command like this:

ar rc my_library.a file1.o file2.o

This command adds the object files file1.o and file2.o to the static library my_library.a, creating my_library.a if it doesn’t already exist.

The command used to create or update the index is called ‘ranlib’, and is invoked as follows:

ranlib my_library.a

On some systems, the archiver (ar) already takes care of the index, so ranlib is not needed.

In this live coding example, you can see that I have two files (file1.c and file2.c) which will eventually end in “.o” after compilation. After compilation, I am able to create my library that contains these files.

How to use them:

To use a static library you can invoke it as part of the compilation process when creating a program executable. If you’re using gcc(1) to generate your executable, you can use the -l option to specify the library.

That’s all, and thanks for reading about this crash course on static libraries. See ya, next time!

Student at Holberton School

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store