Static Libraries with GCC in Linux

Why use libraries

A library contains several object files that can be used during the linking phase of a program. Object files ordered in a library is faster than linking a programs with objects separately on the disk. Also, when using a library, we have fewer files to look for and open, this speeds up linking, which contributes to faster compilation time.

Dynamic loading makes launching the program slightly slower, but this is a very insignificant drawback, that is out-weighted by a great advantage. If a second program linked with the same shared library is executed, it can use the same copy of the shared library, which saves a lot of memory.

How they work

Using a shared library is done in two steps:

  1. Compile Time — The linker scan the shared library while building the executable program, so it will be convinced that no symbols are missing. It will not really take the object files from the shared library and insert them into the program.
  2. Run Time — The system’s dynamic loader (the process in charge of automatically loading and linking shared libraries into the running process) where to find our shared library.

How to create them

  1. A static library is basically a set of object files that were copied into a single file.

gcc -Wall -Werror -Wextra -pedantic -c *.c

The -c flags sats not to run the link, then the output consists of object files output by the assembler.

2. Archive the object files

ar rc libutil.a util_file.o util_net.o util_math.o

'ar' stands for 'archiver'. This program can be used to create static libraries (which are actually archive files), modify object files in the static library, list the names of object files in the library, and so on. In order to create a static library, we can use a command like this:

The 'c' flag tells ar to create the library if it doesn't exist. The 'r' flag replace older object files in the library, with the new object files.

How to use them

gcc main.0 -L -lutil -o prog

The linker will look for the file and link it to the program using the -L. flag.