经过更多的研究,我意识到这些东西是如何工作的。有两个链接器选项可以操作共享库的未定义符号:
第一个是--no-undefined
. 它在链接阶段报告未立即解析的未解析符号。除非在链接的共享库中找到符号,否则手动(使用-l
开关)或自动(libgcc_s
C++ 运行时; libc
C 运行时;ld-linux-**.so
动态链接器实用程序)选择,--no-undefined
将其报告为错误。这就是提问者需要的关键。
还有另一个键,--no-allow-shlib-undefined
(其描述也暗示--no-undefined
)。它检查您链接共享库的共享库中的定义是否满足。此密钥在本主题中显示的情况下用处不大,但它可能很有用。但是,它有自己的障碍。
手册页提供了一些关于为什么它不是默认值的理由:
--allow-shlib-undefined
--no-allow-shlib-undefined
Allows (the default) or disallows undefined symbols in shared
libraries (It is meant, in shared libraries _linked_against_, not the
one we're creating!--Pavel Shved). This switch is similar to --no-un-
defined except that it determines the behaviour when the undefined
symbols are in a shared library rather than a regular object file. It
does not affect how undefined symbols in regular object files are
handled.
The reason that --allow-shlib-undefined is the default is that the
shared library being specified at link time may not be the same as
the one that is available at load time, so the symbols might actually
be resolvable at load time. Plus there are some systems, (eg BeOS)
where undefined symbols in shared libraries is normal. (The kernel
patches them at load time to select which function is most appropri-
ate for the current architecture. This is used for example to dynam-
ically select an appropriate memset function). Apparently it is also
normal for HPPA shared libraries to have undefined symbols.
问题是上面所说的也是正确的,例如,对于 Linux 系统,共享库的一些内部例程是在ld-linux.so
动态加载程序(它既是可执行文件又是共享库)中实现的。除非你以某种方式链接它,否则你会得到这样的东西:
/lib64/libc.so.6: undefined reference to `_dl_argv@GLIBC_PRIVATE'
/lib64/libc.so.6: undefined reference to `_rtld_global_ro@GLIBC_PRIVATE'
/usr/lib64/gcc/x86_64-suse-linux/4.3/libstdc++.so: undefined reference to `__tls_get_addr@GLIBC_2.3'
/lib64/libc.so.6: undefined reference to `_rtld_global@GLIBC_PRIVATE'
/lib64/libc.so.6: undefined reference to `__libc_enable_secure@GLIBC_PRIVATE'
这些是来自加载器的未定义引用,ld-linux.so
. 它是特定于平台的(例如,在我的系统上,正确的加载程序是/lib64/ld-linux-x86-64.so
)。您可以将加载程序与您的库链接,甚至检查上面显示的棘手引用:
g++ -fPIC -shared -o liba.so a.o -Wl,--no-allow-shlib-undefined /lib64/ld-linux-x86-64.so.2