2.4.6. Using a dynamic library with the GCC
Dynamic libraries are available as standalone executable files, required at both linking time and run time. They stay independent of your application’s executable file.
Prerequisites
- GCC must be installed on the system.
- A set of source or object files forming a valid program, requiring some dynamic library foo and no other libraries.
- The foo library must be available as a file libfoo.so.
Procedure
To link a program against a dynamic library foo:
$ gcc ... -Llibrary_path -lfoo ...To use a
run pathvalue stored in the executable file:The
run pathis a special value saved as a part of an executable file when it is being linked. Later, when the program is loaded from its executable file, the runtime linker uses therun pathvalue to locate the library files.While linking with GCC, store the path library_path as
run path:$ gcc ... -Llibrary_path -lfoo -Wl,-run path=library_path ...The path library_path must point to a directory containing the file libfoo.so.
重要Do not add a space after the comma in the
-Wl,-run path=option.Run the program:
$ ./programOn Red Hat Enterprise Linux 10, the
run pathencoded in the program during linking is used only if the linked libraries are not found inLD_LIBRARY_PATH. You can use the-Wl,--disable-new-dtagsoption to restore the old behaviour in Red Hat Enterprise Linux 10, where the run path is searched before theLD_LIBRARY_PATH.
To use the
LD_LIBRARY_PATHenvironment variable:Another way to set search paths to locate libraries is to use the
LD_LIBRARY_PATHenvironment variable. The value of this variable must be changed for each program. This value should represent the path where the shared library objects are located and must be set for every program invocation.Set the
LD_LIBRARY_PATHenvironment variable:$ export LD_LIBRARY_PATH=library_path:$LD_LIBRARY_PATHRun the program:
$ ./program
Optional: Place the library into the default directories.
The runtime linker configuration specifies a number of directories as a default location of dynamic library files. To use this default behaviour, copy your library to the appropriate directory.