我有一个链接到 libdl.so 的程序的 make 文件,其中包含以下行 -ldl。没有调用 dlopen 或任何相关函数。即使您不使用任何函数,以这种方式链接到该库会产生什么影响?
最佳答案
您必须阅读链接器的文档。来 self 的 Linux/ELF/GNU Binutils 系统上的 info ld
(强调已添加):
`--as-needed' `--no-as-needed' This option affects ELF DT_NEEDED tags for dynamic libraries mentioned on the command line after the `--as-needed' option. Normally the linker will add a DT_NEEDED tag for each dynamic library mentioned on the command line, regardless of whether the library is actually needed or not. `--as-needed' causes a DT_NEEDED tag to only be emitted for a library that satisfies an undefined symbol reference from a regular object file or, if the library is not found in the DT_NEEDED lists of other libraries linked up to that point, an undefined symbol reference from another dynamic library. `--no-as-needed' restores the default behaviour.
You can check yourself by running ldd
on a test program. On a simple test program, I get:
linux-vdso.so.1 => (0x00007fffd8305000)
libc.so.6 => /lib/libc.so.6 (0x00007f646c669000)
/lib/ld-linux-x86-64.so.2 (0x00007f646c9ca000)
但是,如果我使用 -ldl
链接,我会得到:
linux-vdso.so.1 => (0x00007fff644f1000)
libdl.so.2 => /lib/libdl.so.2 (0x00007fb9b1375000)
libc.so.6 => /lib/libc.so.6 (0x00007fb9b1014000)
/lib/ld-linux-x86-64.so.2 (0x00007fb9b1579000)
即使我的程序没有使用 libdl
。但是,如果我使用 -Wl,--as-needed
运行 GCC,则不会链接 libdl
。根据我的测试,这仅在 - wl,--as-needed
列在命令行 before -ldl
.
有什么影响?这意味着即使您不使用共享库,您的二进制文件也不会在没有共享库的系统上运行。这也意味着如果您升级共享库并卸载旧的,您的二进制文件将会损坏。这没什么大不了的,因为二进制兼容性无论如何都是一个熊,但我认为没有理由不为一般项目打开 -Wl,--as-needed
。
关于c - 链接到您不对其进行函数调用的库有什么影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6411937/