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 path value stored in the executable file:

    The run path is 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 the run path value to locate the library files.

    1. 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.

    2. Run the program:

      $ ./program

      On Red Hat Enterprise Linux 10, the run path encoded in the program during linking is used only if the linked libraries are not found in LD_LIBRARY_PATH. You can use the -Wl,--disable-new-dtags option to restore the old behaviour in Red Hat Enterprise Linux 10, where the run path is searched before the LD_LIBRARY_PATH.

  • To use the LD_LIBRARY_PATH environment variable:

    Another way to set search paths to locate libraries is to use the LD_LIBRARY_PATH environment 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.

    1. Set the LD_LIBRARY_PATH environment variable:

      $ export LD_LIBRARY_PATH=library_path:$LD_LIBRARY_PATH
    2. Run 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.

Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

关于红帽文档

Legal Notice

Theme

© 2026 Red Hat
返回顶部