【问题标题】:Why does the linker complain “file was built for archive which is not the architecture being linked” when the architecture is correct?当架构正确时,为什么链接器会抱怨“文件是为归档而不是被链接的架构而构建的”?
【发布时间】:2019-01-24 10:03:21
【问题描述】:

当尝试构建一个使用 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

但根据lipo,架构正确一致 (x86_64):

⟩⟩⟩ 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

【问题讨论】:

  • 此错误消息还有许多其他问题,但这些都与由于交叉编译导致的实际架构不匹配有关。我问了这个问题是因为目前无法通过谷歌搜索与我遇到相同问题的人的错误消息。希望这对其他人有帮助。
  • 而且,如果有人对轶事感兴趣:调试和修复这个问题在复杂的代码库中花了我几天时间。

标签: macos clang ld unix-ar


【解决方案1】:

错误消息实际上具有误导性:问题不是架构不匹配,而是静态库(.a 文件)不能嵌套:

⟩⟩⟩ nm bar.a

bar.a(bar.o):
0000000000000000 T _bar

(请注意,foo.a 中的条目 _foo 丢失了!)

但由于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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多