nasm -f elf -o kernel.o kernel.asm
nasm -f elf -o string.o string.asm
nasm -f elf -o kliba.o kliba.asm
gcc -c -fno-builtin -o start.o start.c
ld -s -Ttext 0x30400 -o kernel.bin kernel.o \
string.o start.o kliba.o
来编译与链接代码的话,在链接目标文件时会报错:
ld -s -Ttext 0x30400 -o kernel.bin kernel.o \
> string.o start.o kliba.o
ld: i386 architecture of input file `kernel.o' is incompatible with i386:x86-64 output
ld: i386 architecture of input file `string.o' is incompatible with i386:x86-64 output
ld: i386 architecture of input file `kliba.o' is incompatible with i386:x86-64 output
因为我的开发平台为64位Ubuntu,而本书是以32位汇编进行内核开发,所以上面32位的汇编程序编译后得到的目标文件不能与64位的Ubuntu默认的64位二进制输出兼容,于是在链接命令中添加参数:-m elf_i386,即
ld -m elf_i386 -s -Ttext 0x30400 -o kernel.bin kernel.o string.o start.o kliba.o
使链接得到的二进制文件为32位。该命令执行结果是:
ld: i386:x86-64 architecture of input file `start.o' is incompatible with i386 output
说明在指定ld链接命令得到的二进制文件为32位后,64位Ubuntu的gcc默认情况下编译start.c得到的64位start.o,无法与32位的二进制文件输出格式兼容,所以此时对gcc命令进行以下修改:
gcc -m32 -c -fno-builtin -o start.o start.c
使得start.c文件编译得到的目标文件为32位。最后运行链接命令,成功得到kernel.bin文件。