动态链接时,它将在哪里搜索库,以及如何更改它



当我在基于 Unix/Linux 的系统上动态链接时,当我执行程序时,它会尝试在哪里查找库文件,我该如何更改它?我正在使用GNU/G++编译器。

程序运行的系统定义了在何处搜索动态库。 程序本身只是命名库(没有路径)。

在 Linux 系统上,有一个系统范围的默认值进行搜索,您可以通过将环境变量LD_LIBRARY_PATH设置为以冒号分隔的库路径列表来覆盖它:

$ LD_LIBRARY_PATH=/path/to/my/libs/:/another/path/to/libs/of/mine/
$ export LD_LIBRARY_PATH
$ ./path/to/my/executable

或更短:

$ LD_LIBRARY_PATH=/path/to/my/libs/:/another/path/to/libs/of/mine/ ./path/to/my/executable

系统默认值使用 ldconfig 进行配置,通常基于 /etc/ld.so.conf (指向 /etc/ld.so.conf.d ) 和 /etc/ld.so.cache 中找到的文件。

可以使用ldd检查给定可执行文件将需要哪些动态库:

$ ldd /bin/ls
    linux-vdso.so.1 =>  (0x00007fffc83ff000)
    libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007fbe1306b000)
    librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007fbe12e63000)
    libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007fbe12c5a000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fbe1289b000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fbe12697000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fbe132ae000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fbe12479000)
    libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007fbe12274000)

您还可以在启动可执行文件时使用 strace 的输出来查看系统查找库的位置:

$ strace ls 2>&1 | grep '^open.*.so'
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libselinux.so.1", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/librt.so.1", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libacl.so.1", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libdl.so.2", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libattr.so.1", O_RDONLY|O_CLOEXEC) = 3

最新更新