2.4.5. Linking static libraries with the GCC
To link static libraries, bundle them as archives that contain object files. After linking, they become part of the resulting executable file. Static linking overrides the default dynamic linking behavior.
Red Hat discourages use of static linking for security reasons. See Static and dynamic linking. Use static linking only when necessary, especially against libraries provided by Red Hat.
Most libraries that are part of Red Hat Enterprise Linux support dynamic linking only. The remaining steps in this procedure apply only to libraries that do not support dynamic linking.
Prerequisites
- GCC must be installed on your system.
- You must understand static and dynamic linking.
- You have a set of source or object files forming a valid program, requiring some static library foo and no other libraries.
-
The foo library is available as a file
libfoo.a, and no filelibfoo.sois provided for dynamic linking.
See Static and dynamic linking
Procedure
To link a program from source and object files, adding a statically linked library foo, which is to be found as a file
libfoo.a.- Change to the directory containing your code.
Compile the program source files with headers of the foo library:
$ gcc ... -Iheader_path -c ...Replace header_path with a path to a directory containing the header files for the foo library.
Link the program with the foo library:
$ gcc ... -Llibrary_path -lfoo ...Replace library_path with a path to a directory containing the file
libfoo.a.To run the program later:
$ ./program警告The
-staticGCC option related to static linking forbids all dynamic linking. Instead, use the-Wl,-Bstaticand-Wl,-Bdynamicoptions to control linker behavior more precisely. See Static and dynamic libraries with GCC.