gpt4 book ai didi

linux - 如何将存档的所有对象包含在共享对象中?

转载 作者:行者123 更新时间:2023-11-30 17:04:21 25 4
gpt4 key购买 nike

编译项目时,我们创建几个文件(静态库),例如 liby.alibz.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

当在示例程序中使用此共享对象时,例如 x.c,由于未定义对函数 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

知道这是从哪里来的吗?

最佳答案

你可以尝试(ld(2)):

   --whole-archive
For each archive mentioned on the command line after the --whole-archive option, include every object file in the
archive in the link, rather than searching the archive for the required object files. This is normally used to turn
an archive file into a shared library, forcing every object to be included in the resulting shared library. This
option may be used more than once.

(gcc -Wl,--整个存档)

另外,您应该将 -Wl,--no-whole-archive 放在库列表的末尾。 (正如德米特里·尤达科夫在下面的评论中所说)

关于linux - 如何将存档的所有对象包含在共享对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35840039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com