Node:Libraries, Next:Arrays, Previous:Preprocessor directives, Up:Top
Libraries
Plug-in C expansions. Header files.
The core of the C language is small and simple, but special functionality is provided in the form of external libraries of ready-made functions. Standardized libraries make C code extremely portable, or easy to compile on many different computers.
Libraries are files of ready-compiled code that the compiler merges, or links, with a C program during compilation. For example, there are libraries of mathematical functions, string handling functions, and input/output functions. Indeed, most of the facilities C offers are provided as libraries.
Some libraries are provided for you. You can also make your own, but to do so, you will need to know how GNU builds libraries. We will discuss that later. (See Building a library.)
Most C programs include at least one library. You need to ensure both that the library is linked to your program and that its header files are included in your program.
The standard C library, or glibc
, is linked automatically with
every program, but header files are never included automatically, so you
must always include them yourself. Thus, you must always include
stdio.h
in your program if you intend to use the standard
input/output features of C, even though glibc
, which contains the
input/output routines, is linked automatically.
Other libraries, however, are not linked automatically. You must link
them to your program yourself. For example, to link the math library
libm.so
, type
gcc -o program_name program_name.c -lm
The command-line option to link libm.so
is simply -lm
,
without the lib
or the .so
, or in the case of static
libraries, .a
. (See Kinds of library.)
The -l
option was created because the average GNU system
already has many libraries, and more can be added at any time. This
means that sometimes two libraries provide alternate definitions of the
same function. With judicious use of the -l
option, however,
you can usually clarify to the compiler which definition of the function
should be used. Libraries specified earlier on the command line take
precedence over those defined later, and code from later libraries is
only linked in if it matches a reference (function definition,
macro, global variable, etc.) that is still undefined. (See Compiling multiple files, for more information.)
In summary, you must always do two things:
- link the library with a
-l
option to gcc (a step that may be skipped in the case ofglibc
). - include the library header files (a step you must always
follow, even for
glibc
).