【发布时间】:2021-04-21 07:16:13
【问题描述】:
目标
我想创建一个共享库libsquare.so,它静态链接到libmul.a,它本身静态链接到libadd.a
情况
我通过将libadd.a 链接到它来创建libmul.a。
然后我通过链接刚刚创建的libmul.a 来创建libsquare.so。
libmul.a 具有add 函数的代码。
问题
当我将它链接到共享对象并查看符号表时,add-symbol 仍然存在,但未定义 (*UND*),而不是在 .text 部分中。
我有一个 MWE here on Github 演示它。
这里是objdump -t libsquare.so的一部分
libsquare.so: file format elf64-x86-64
SYMBOL TABLE:
0000000000000000 *UND* 0000000000000000 add
0000000000001119 g F .text 000000000000001c square
0000000000001135 g F .text 000000000000003b mul
... // some symbols omitted here... See repo for entire table
这里是整个objdump -t libmul.a
mul.o: file format elf64-x86-64
SYMBOL TABLE:
0000000000000000 l df *ABS* 0000000000000000 mul.c
0000000000000000 l d .text 0000000000000000 .text
0000000000000000 g F .text 000000000000003b mul
0000000000000000 *UND* 0000000000000000 _GLOBAL_OFFSET_TABLE_
0000000000000000 *UND* 0000000000000000 add
In nested archive libadd.a:
add.o: file format elf64-x86-64
SYMBOL TABLE:
0000000000000000 l df *ABS* 0000000000000000 add.c
0000000000000000 l d .text 0000000000000000 .text
0000000000000000 g F .text 0000000000000014 add
本质上运行的命令是:
cc -fPIC -rdynamic -o add.o -c add.c
cc -fPIC -rdynamic -o mul.o -c mul.c
cc -fPIC -rdynamic -o square.o -c square.c
ar rcs libadd.a add.o
ranlib libadd.a
ar rcs libmul.a mul.o libadd.a
ranlib libmul.a
gcc -shared -Wl,-soname=square -o libsquare.so square.o libmul.a
cc -fPIC -rdynamic -o test-w-lib.o -c test-w-lib.c
cc -o test-w-lib libsquare.so test-w-lib.o -ldl
/usr/bin/ld: libsquare.so: undefined reference to `add'
collect2: error: ld returned 1 exit status
【问题讨论】:
-
只是
gcc -shared -Wl,-soname=square -o libsquare.so square.o mul.o add.o。which is statically linked如果您希望它们包含在库中,则解压缩静态库并与目标文件链接。 -
你所说的包含是什么意思?假设,我无权访问
add.o,它是一个具有自己依赖项的不同项目,我只能获得libadd.o。 -
包含我的意思是共享库将包含其中的所有代码。 “静态链接”是什么意思?静态链接仅意味着编译。解压缩静态库并从中提取目标文件。然后用目标文件编译。静态库只是列出 .o 文件的“zip”,仅此而已。 ||或者使用
--whole-archive,它与在编译行中包含所有目标文件一样。 stackoverflow.com/questions/2649735/… 会回答你的问题吗? -
这个答案提到了拆包 stackoverflow.com/questions/8808691/… 。它回答了你的问题吗?在提出问题之前您做了哪些研究?
-
"libmul.a 有 add-function 的代码。":你怎么想的?这是错的。只需使用
gcc -shared -Wl,-soname=square -o libsquare.so square.o libmul.a libadd.a
标签: c linker static-libraries dynamic-library