macos - 当架构正确时,为什么链接器会抱怨“文件是为归档而不是被链接的架构而构建的”?
问题描述
尝试构建使用 clang 链接静态库的二进制文件(请参阅下面的 MWE)时,我收到以下错误消息:
⟩⟩⟩ clang -o test bar.a test.o
ld: warning: ignoring file bar.a, file was built for archive which is not the architecture being linked (x86_64): bar.a
> Undefined symbols for architecture x86_64:
> "_bar", referenced from:
> _main in test.o
> "_foo", referenced from:
> _main in test.o
> ld: symbol(s) not found for architecture x86_64
但是架构是正确且一致的(x86_64),根据lipo
:
⟩⟩⟩ lipo -info test.o bar.a
input file bar.a is not a fat file
Non-fat file: test.o is architecture: x86_64
Non-fat file: bar.a is architecture: x86_64
otools -hv
显示类似的输出。所有目标文件都是为 x86_64 构建的。那么这个错误信息是什么意思呢?
这是一个完整的,最小的,工作示例来重现上面显示的问题:
foo.c
:int foo(void) { return 1; }
bar.c
:int bar(void) { return 2; }
test.c
:#include <stdio.h> int foo(void); int bar(void); int main(void) { printf("foo = %d\n", foo()); printf("bar = %d\n", bar()); }
汇编:
clang -c -o foo.o foo.c
ar rcs foo.a foo.o
clang -c -o bar.o bar.c
ar rcs bar.a foo.a bar.o
clang -c -o test.o test.c
clang -o test bar.a test.o
解决方案
错误消息实际上具有误导性:问题不是架构不匹配,而是静态库(.a
文件)不能嵌套:
⟩⟩⟩ nm bar.a
bar.a(bar.o):
0000000000000000 T _bar
(请注意,缺少_foo
来自的条目!)foo.a
但由于ar
最初是一个通用的存档实用程序,因此它可以毫无疑虑地通过以下方式创建嵌套存档
ar rcs bar.a foo.a bar.o
我们可以通过列出其内容来验证:
⟩⟩⟩ ar t bar.a
__.SYMDEF SORTED
foo.a
bar.o
要解决此问题,请不要嵌套存档,而是直接打包目标文件:
rm bar.a
ar rcs bar.a foo.o bar.o
clang -o test bar.a test.o
推荐阅读
- node.js - jsftp - TypeError:createConnection 不是函数
- python - 如何在 iTerm2 窗口上执行 bash 脚本 onHover?
- javascript - 添加逗号 JavaScript 计数器
- python - 根据其值为pandas dataFrame分配一个替代值
- c# - HttpPostedFileBase 在 ASP.NET MVC 中返回 NULL
- android - 阻止人们访问专用于 Web 应用程序的网页
- javascript - 字符串数组的元素级联
- python - 模块 : - 跨 Python 模块共享全局变量
- python - 记录烧瓶应用程序
- unity3d - Unity - 关闭环境光不会让我的场景完全变黑