In the previous section, we created a library named mylib from three object files called index.o, addtwo.o, and addthree.o. Now we want to use that library to compile an application called six.c:
int main(void)
{
int i, j;
inc(); inc();
i = show();
j = addthree (i, show(), 4);
return j;
}
Here, we use the library functions inc()
, show()
,
and addthree()
. These are all contained in the library
mylib, so all we need to do is link that with
six.c to form the executable Six:
cc -o Six six.c mylib
After compilation, the executable Six will contain the modules
which contain the functions inc()
, show()
, and
addthree()
, but none of the other modules that were archived in
mylib. Thus, is contains the code for dec()
, but
not for addtwo()
.
Library search paths
By default, the linker will search for a library in one of several directories.
These usually include /lib and /usr/lib, but can include others. Libraries
that reside in these directories can be included easily if they conform to a
specific naming convention.
When we compile an executable, we can use the -lname
switch to tell the compiler to look in its search path for the named library.
However, what it will actually look for is the file named
libname.a
. This means that we would have been better
off to name our library libmylib.a instead of just
mylib. If we change the name we can put our library in a
directory on the search path and use the following command line to link
Six.
cc -o Six six.c -lmylib
Finally, if we don't have write access to the directories on the search path,
we can add a directory to the search path by using the
-Ldirectory
switch:
cc -o Six six.c -Lsomedirectory -lmylib
Now, the compiler (actually the static linker) will look in the directory
somedirectory for the library archive file libmylib.a
.
This page was last modified
.