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
.