首页 > 解决方案 > 当架构正确时,为什么链接器会抱怨“文件是为归档而不是被链接的架构而构建的”?

问题描述

尝试构建使用 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 构建的。那么这个错误信息是什么意思呢?


这是一个完整的,最小的,工作示例来重现上面显示的问题:

汇编:

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

标签: macosclangldunix-ar

解决方案


错误消息实际上具有误导性:问题不是架构不匹配,而是静态库(.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

推荐阅读