【发布时间】:2021-05-17 21:35:24
【问题描述】:
我正在尝试首次涉足图书馆。我正在尝试使用 gcc -c -fPIC -std=c99 -Wall -Wextra -pedantic -Werror -Wmissing-declarations -DUNITY_SUPPORT_64 test-framework/unity.c -o bin/libunity.o 将 Unity 测试框架编译为静态库
这运行得很好。
但是,当我尝试使用该目标文件时:
$ gcc test_hello_world.c -Lbin -lunity -o test
/usr/bin/ld: cannot find -lunity
collect2: error: ld returned 1 exit status
检查 ld 正在做什么
$ ld -Lbin -luinty --verbose
GNU ld (GNU Binutils for Ubuntu) 2.34
Supported emulations:
elf_x86_64
elf32_x86_64
#
# ... script waffle
#
==================================================
ld: mode elf_x86_64
attempt to open bin/libuinty.so failed
attempt to open bin/libuinty.a failed
attempt to open /usr/local/lib/x86_64-linux-gnu/libuinty.so failed
attempt to open /usr/local/lib/x86_64-linux-gnu/libuinty.a failed
attempt to open /lib/x86_64-linux-gnu/libuinty.so failed
attempt to open /lib/x86_64-linux-gnu/libuinty.a failed
attempt to open /usr/lib/x86_64-linux-gnu/libuinty.so failed
attempt to open /usr/lib/x86_64-linux-gnu/libuinty.a failed
attempt to open /usr/lib/x86_64-linux-gnu64/libuinty.so failed
attempt to open /usr/lib/x86_64-linux-gnu64/libuinty.a failed
attempt to open /usr/local/lib64/libuinty.so failed
attempt to open /usr/local/lib64/libuinty.a failed
attempt to open /lib64/libuinty.so failed
attempt to open /lib64/libuinty.a failed
attempt to open /usr/lib64/libuinty.so failed
attempt to open /usr/lib64/libuinty.a failed
attempt to open /usr/local/lib/libuinty.so failed
attempt to open /usr/local/lib/libuinty.a failed
attempt to open /lib/libuinty.so failed
attempt to open /lib/libuinty.a failed
attempt to open /usr/lib/libuinty.so failed
attempt to open /usr/lib/libuinty.a failed
attempt to open /usr/x86_64-linux-gnu/lib64/libuinty.so failed
attempt to open /usr/x86_64-linux-gnu/lib64/libuinty.a failed
attempt to open /usr/x86_64-linux-gnu/lib/libuinty.so failed
attempt to open /usr/x86_64-linux-gnu/lib/libuinty.a failed
ld: cannot find -luinty
所以它会寻找bin/libunity.so 和bin/libunity.a,但没有bin/libunity.o...我今晚查看的每个互联网页面似乎都假设 ld 应该拾取“.o”文件,就像“.so”或“.a”不问任何问题(手册页似乎同样期待它或根本不提及“.o”)......但它不是......
我是不是误会了什么?缺少一些论点?
编辑:我现在运行ar rcs bin/libunity.a bin/unity.o,然后从上面运行gcc 命令。这似乎可以工作(还有其他错误)。但我仍然认为 ld 应该使用 .o 文件,是我和一半的网络,错了吗?
【问题讨论】:
-
gcc test_hello_world.c bin/libunity.o -o test应该可以工作。从未听说过lib*.o文件可以替代lib*.so/lib*.a文件。*.o文件直接链接。没有lib*foo.o=>-lfoo魔法。 -
我什至会犹豫是否使用“库”这个词来描述 .o 文件。如果您发现“一半的网络”将 .o 文件称为库,那么我同意一半的网络是错误的。
-
或者如果你想把你的
.o变成.a、ar -crs libunity.a libunity.o、See also。静态库是一个包含一个或多个目标文件的ar存档。 -
但是如果有一半的网络是错误的,我会感到非常惊讶。更像是 95% 是不正确的。
-
一半的网络可能是*轻微的夸张:D,我检查的 6-7 个网站都相互不同意,但所有预期的 .o 文件都可以链接。