Compiling a library of objects

In the previous section, we saw that we can write modular code using objects and that we can minimize the size of these objects by separating sources. This we found leaves a large number of object files which we need to keep track of. A library is a collection of objects into a single file which the linker understands and from which it can choose only the modules necessary to create the executable that it is trying to create. In this section we will talk about creating libraries.

The UNIX archiver

UNIX systems have an archiver program called ar, whose purpose is to store multiple files in a single file from which it can extract the originals. A UNIX library is just an archive of object files from which the linker can grab just the object files it needs.

In the previous section, we had a three sources which we compiled to three object files called index.o, addtwo.o, and addthree.o. Let's combine these using the archiver into a single library file. To do this, we will use the -c switch and create a library named mylib:


	ar -c mylib index.o addtwo.o addthree.o
Now we have an archive file named mylib which contains our
object files.  We can now delete these files so that we have fewer files lying
around.

If we later want to add more objects to an existing library, we can use the -q switch to append the object to the end of the library:


	ar -q mylib newobject.o

If we want to update one of the objects that is already in the library, we can use the -r switch to replace the object in the library:


	ar -r mylib addthree.o

Static versus Dynamic Libraries

The library created above is called a static library, because the code it contains is linked with other code when the executable is built. The resulting executable file does not require any other pieces in order to run. A dynamic library is one in which the code contained inside it is linked with other code only when the program is about to be run.

These libraries are used because they minimize the size of the files that are created. During compilation, only part of the executable is actually created. When one of these dynamically-linked programs is run by the user, a dynamic linker links the partial executable with the necessary objects in the dynamic library, then loads the program for running.

I will write more about dynamic libraries on some future date.


This page was last modified .