Datasheet

Standard system libraries are usually stored in /lib and /usr/lib. The C compiler (or more exactly, the
linker) needs to be told which libraries to search, because by default it searches only the standard C library.
This is a remnant of the days when computers were slow and CPU cycles were expensive. It’s not enough
to put a library in the standard directory and hope that the compiler will find it; libraries need to follow a
very specific naming convention and need to be mentioned on the command line.
A library filename always starts with
lib. Then follows the part indicating what library this is (like c for
the C library, or
m for the mathematical library). The last part of the name starts with a dot (.), and specifies
the type of the library:
.a for traditional, static libraries
.so for shared libraries (see the following)
The libraries usually exist in both static and shared formats, as a quick
ls /usr/lib will show. You
can instruct the compiler to search a library either by giving it the full path name or by using the
-l
flag. For example,
$ gcc -o fred fred.c /usr/lib/libm.a
tells the compiler to compile file fred.c, call the resulting program file fred, and search the mathematical
library in addition to the standard C library to resolve references to functions. A similar result is achieved
with the following command:
$ gcc -o fred fred.c -lm
The -lm (no space between the l and the m) is shorthand (shorthand is much valued in UNIX circles)
for the library called
libm.a in one of the standard library directories (in this case /usr/lib). An addi-
tional advantage of the
-lm notation is that the compiler will automatically choose the shared library
when it exists.
Although libraries are usually found in standard places in the same way as header files, you can add to
the search directories by using the
-L (uppercase letter) flag to the compiler. For example,
$ gcc -o x11fred -L/usr/openwin/lib x11fred.c -lX11
will compile and link a program called x11fred using the version of the library libX11 found in the
/usr/openwin/lib directory.
Static Libraries
The simplest form of library is just a collection of object files kept together in a ready-to-use form. When a
program needs to use a function stored in the library, it includes a header file that declares the function.
The compiler and linker take care of combining the program code and the library into a single executable
program. You must use the
–l option to indicate which libraries other than the standard C runtime library
are required.
Static libraries, also known as archives, conventionally have names that end with
.a. Examples are /usr/
lib/libc.a
and /usr/lib/libX11.a for the standard C library and the X11 library, respectively.
10
Chapter 1: Getting Started
47627c01.qxd:WroxPro 9/28/07 8:56 PM Page 10