2.4.4. Library use with GCC
A library is a reusable package of code. A C or C++ library consists of the library code and header files.
- Compiling code that uses a library
- The header files describe the interface of the library: the functions and variables available in the library. Information from the header files is needed for compiling the code.
Typically, header files of a library will be placed in a different directory than your application’s code. To tell GCC where the header files are, use the -I option:
$ gcc ... -Iinclude_path ...
Replace include_path with the actual path to the header file directory.
For example, to specify a relative path some/interesting/directory:
$ gcc ... -Isome/interesting/directory ...
The -I option can be used multiple times to add multiple directories with header files. When looking for a header file, these directories are searched in the order of their appearance in the -I options.
- Linking code that uses a library
When linking the executable file, both the object code of your application and the binary code of the library must be available. The code for static and dynamic libraries is present in different forms:
-
Static libraries are available as archive files. They contain a group of object files. The archive file has a file name extension
.a. -
Dynamic libraries are available as shared objects. They are a form of an executable file. A shared object has a file name extension
.so.
-
Static libraries are available as archive files. They contain a group of object files. The archive file has a file name extension
To tell GCC where the archives or shared object files of a library are, use the -L option:
$ gcc ... -Llibrary_path -lfoo ...
Replace library_path with the actual path to the library directory.
The -L option can be used multiple times to add multiple directories. When looking for a library, these directories are searched in the order of their -L options.
The order of options matters: GCC cannot link against a library foo unless it knows the directory with this library. Therefore, use the -L options to specify library directories before using the -l options for linking against libraries.
- Compiling and linking code which uses a library in one step
-
When you compile and link in a single
gcccommand, combine the compile-time and link-time options.