Node:Kinds of library, Next:, Previous:Header files, Up:Libraries

Kinds of library

There are two kinds of library: static libraries and shared libraries. When you link to a static library, the code for the entire library is merged with the object code for your program. If you link to many static libraries, your executable will be enormous.

Shared libraries were developed in the late 1980s to reduce the code size of programs on operating systems like GNU. When you link to a shared library, the library's code is not merged with your program's object code. Instead, stub code is inserted into your object code. The stub code is very small and merely calls the functions in the shared library -- the operating system does the rest. An executable created with a shared library can therefore be far smaller than one created with a static library. Shared libraries can also reduce the amount of memory used.

Although shared libraries seem to have every advantage over static libraries, static libraries are still useful. For example, sometimes you will wish to distribute an executable to people whose computers do not have the libraries that yours does. In that case, you might link to a static version of the libraries. This will incorporate the library functions that you need into your executable, so that it will run on systems that don't have those libraries. (It is also sometimes easier to debug a program that is linked to static libraries than one linked to shared libraries. See Introduction to GDB, for more information.)

The file name for a library always starts with lib and ends with either .a (if it is static) or .so (if it is shared). For example, libm.a is the static version of the C math library, and is the shared version. As explained above, you must use the -l option with the name of a library, minus its lib prefix and .a or .so suffix, to link that library to your program (except the library glibc, which is always linked). For example, the following shell command creates an executable program called math from the source code file math.c and the library

gcc -o math math.c -lm

The shared version of the library is always linked by default. If you want to link the static version of the library, you must use the GCC option --static. The following example links libm.a instead of

gcc -o math math.c -lm --static

Type info gcc at your shell prompt for more information about GCC options.