報錯:ld: i386 架構於輸入文件 foo.o 與 i386:x86-64 輸出不兼容
或者:ld: i386 architecture of input file `foo.o' is incompatible with i386:x86-64 output
編譯鏈接指令
1
nasm -f elf foo.s -o foo.o
2
gcc -c bar.c -o bar.o
3
ld -s -o foobar bar.o foo.o
匯編語言用nasm編寫並用nasm編譯器編譯,而C語言用的是gcc編譯,這些都沒有問題,但是在鏈接的時候出錯了,提示如下:
ld: i386 architecture of input file `foo.o' is incompatible with i386:x86-64 output
意思就是nasm 編譯產生的是32位的目標代碼,gcc 在64位平台上默認產生的是64位的目標代碼,這兩者在鏈接的時候出錯,gcc在64位平台上默認以64位的方式鏈接。
這樣在解決的時候就會有兩種解決方案:
<1> 讓gcc 產生32位的代碼,並在鏈接的時候以32位的方式進行鏈接
在這種情況下只需要修改編譯和鏈接指令即可,具體如下:
32位的編譯鏈接指令
1
nasm -f elf foo.s -o foo.o
2
gcc -m32 -c bar.c -o bar.o
3
ld -m elf_i386 -s -o foobar foo.o bar.o
具體的-m32 和 -m elf_i386 請自行查閱gcc (man gcc)
如果你是高版本的gcc(可能是由於更新內核造成的),可能簡單的使用-m32 的時候會提示以下錯誤(使用別人的歷程,自己未曾遇到):
> In file included from /usr/include/stdio.h:28:0,
> from test.c:1:
> /usr/include/features.h:323:26: fatal error: bits/predefs.h: No such file or directory
> compilation terminated.
這應該是缺少構建32 位可執行程序缺少的包,使用以下指令安裝:
sudo apt-get install libc6-dev-i386
此時應該就沒有什么問題了。
參考:https://zhidao.baidu.com/question/1831399869227285020.html