学习操作系统时,链接几个用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