Development System - Library Files
Libraries are collections of precompiled functions that have been written to be reusable. Typically, they consist of sets of related functions to perform a common task. Examples include libraries of screen-handling functions (the curses and ncurses libraries) and database access routines (the dbm library).
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, as 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. We 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 additional 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, we 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.
