ld: i386 architecture of input file `kernel.o‘ is incompatible with i386:x86-64 output

学习操作系统时,链接几个用nasm汇编器生成的elf文件时,出现如题所示的错误提示。
操作如下:

nasm -f elf kernel.asm -o kernel.o
nasm -f elf string.asm -o string.o
nasm -f elf kliba.asm -o kliba.o
gcc -c start.c -o start.o -fno-builtin-memcpy
ld -s -Ttext 0x30400 -o kernel.bin kernel.o kliba.o string.o start.o

报错如下:

ld: i386 architecture of input file `kernel.o' is incompatible with i386:x86-64 output
ld: i386 architecture of input file `kliba.o' is incompatible with i386:x86-64 output
ld: i386 architecture of input file `string.o' is incompatible with i386:x86-64 output

用nasm -hf查看nasm的输出文件格式发现elf格式的种类主要有如下几种:
elf32 ELF32 (i386) object files (e.g. Linux)
elf64 ELF64 (x86_64) object files (e.g. Linux)
elf ELF (short name for ELF32)

原来是那三个可重定位文件都是32位的,而我在64位的Linux系统下使用gcc和ld,默认生成64位的可执行文件。
用ld --help命令查看ld的输出文件格式,其中有提到:
ld: supported emulations: elf_x86_64 elf32_x86_64 elf_i386 elf_iamcu i386linux elf_l1om elf_k1om i386pep i386pe

先将start.c编译成32位的可重定位文件,再进行链接,链接时指定生成32位的文件:

gcc -m32 -c start.c -o start.o -fno-builtin-memcpy
ld -m elf_i386 -s -Ttext 0x30400 -o kernel.bin kernel.o kliba.o string.o start.o

以下是结果:

deal@ubuntu:/mnt/hgfs/Linux_share/OrangeS/chapter5/f$ readelf -h kernel.bin 
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x30400
  Start of program headers:          52 (bytes into file)
  Start of section headers:          4208 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         3
  Size of section headers:           40 (bytes)
  Number of section headers:         8
  Section header string table index: 7

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值