如何将存档的所有对象包含在共享对象中?
编译项目时,我们创建几个档案(静态库),例如 liby.a
和 libz.a
,每个档案都包含一个定义函数 y_function( )
和 z_function()
。然后,这些档案被加入到一个共享对象中,例如libyz.so
,这是我们的主要可分发目标之一。
g++ -fPIC -c -o y.o y.cpp
ar cr liby.a y.o
g++ -fPIC -c -o z.o z.cpp
ar cr libz.a z.o
g++ -shared -L. -ly -lz -o libyz.so
当在示例程序中使用此共享对象时,例如 xc
,链接会失败,因为对函数 y_function()
和 z_function()
的未定义引用>。
g++ x.o -L. -lyz -o xyz
但是,当我将最终的可执行文件直接与档案(静态库)链接时,它会起作用。
g++ x.o -L. -ly -lz -o xyz
我的猜测是,档案中包含的目标文件没有链接到共享库中,因为它们没有在其中使用。如何强制包容?
编辑:
可以使用 --whole-archive ld
选项强制包含。但如果导致编译错误:
g++ -shared '-Wl,--whole-archive' -L. -ly -lz -o libyz.so
/usr/lib/libc_nonshared.a(elf-init.oS): In function `__libc_csu_init':
(.text+0x1d): undefined reference to `__init_array_end'
/usr/bin/ld: /usr/lib/libc_nonshared.a(elf-init.oS): relocation R_X86_64_PC32 against undefined hidden symbol `__init_array_end' can not be used when making a shared object
/usr/bin/ld: final link failed: Bad value
知道这是从哪里来的吗?
When compiling our project, we create several archives (static libraries), say liby.a
and libz.a
that each contains an object file defining a function y_function()
and z_function()
. Then, these archives are joined in a shared object, say libyz.so
, that is one of our main distributable target.
g++ -fPIC -c -o y.o y.cpp
ar cr liby.a y.o
g++ -fPIC -c -o z.o z.cpp
ar cr libz.a z.o
g++ -shared -L. -ly -lz -o libyz.so
When using this shared object into the example program, say x.c
, the link fails because of an undefined references to functions y_function()
and z_function()
.
g++ x.o -L. -lyz -o xyz
It works however when I link the final executable directly with the archives (static libraries).
g++ x.o -L. -ly -lz -o xyz
My guess is that the object files contained in the archives are not linked into the shared library because they are not used in it. How to force inclusion?
Edit:
Inclusion can be forced using --whole-archive ld
option. But if results in compilation errors:
g++ -shared '-Wl,--whole-archive' -L. -ly -lz -o libyz.so
/usr/lib/libc_nonshared.a(elf-init.oS): In function `__libc_csu_init':
(.text+0x1d): undefined reference to `__init_array_end'
/usr/bin/ld: /usr/lib/libc_nonshared.a(elf-init.oS): relocation R_X86_64_PC32 against undefined hidden symbol `__init_array_end' can not be used when making a shared object
/usr/bin/ld: final link failed: Bad value
Any idea where this comes from?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试 (ld(2)):
(gcc -Wl,--whole-archive)
另外,您应该将
-Wl,--no-whole-archive
放在库列表的末尾。 (正如德米特里·尤达科夫在下面的评论中所说)You could try (ld(2)):
(gcc -Wl,--whole-archive)
Plus, you should put
-Wl,--no-whole-archive
at the end of the library list. (as said by Dmitry Yudakov in the comment below)