c - ld: cannot perform PE operations on non PE output file 错误

标签 c gcc mingw ld

我是操作系统编程的新手,我正在阅读一本书,其中给出了一个简单的内核示例,如下所示:

main() {
   char *video_memory = 0xb8000;
   *video_memory = 'X';
}

为了编译这个名为 kernel.c 的文件,我在 Windows 7 下使用 MinGW,如下所示:

gcc -ffreestanding -c kernel.c -o kernel.o

这将创建目标文件 kernel.o。但是,以下命令不起作用。

ld -o kernel.bin -Ttext 0x1000 kernel.o --oformat binary

我收到以下错误:

ld: cannot perform PE operations on non PE output file 'kernel.bin'

我无法解决问题。请帮助我。

谢谢

在Ross的帮助下,我成功跳转到了kernel offset。但是,我无法从 Kernel_entry.asm 调用 C 函数。此外,当我从我的 kernel.bin 中删除 C 函数并如下所示更改代码时,屏幕上显示了三个奇怪的字符。

Kernel_entry.asm 如下:

[bits 32]
;[extern _start]
mov ebx, MSG_KERNEL_ENTRY
call print_string_pm
;call _start
jmp $

%include "print_string_pm.asm"

MSG_KERNEL_ENTRY db "Kernel entry is invoked", 0

bootsec.asm如下:

[org 0x7c00]

KERNEL_OFFSET equ 0x1000

mov [BOOT_DRIVE], dl
mov bp, 0x9000
mov sp, bp
mov bx, MSG_REAL_MODE
call print_string
call load_kernel
call switch_to_pm

jmp $

%include "print_string.asm"
%include "disk_load.asm"
%include "gdt.asm"
%include "print_string_pm.asm"
%include "switch_to_pm.asm"
%include "clear_screen.asm"
[bits 16]
load_kernel:
mov bx, MSG_LOAD_KERNEL
call print_string

mov bx, KERNEL_OFFSET
mov dh, 15
mov dl, [BOOT_DRIVE]
call disk_load

ret


[bits 32]

BEGIN_PM:
;call clear_screen
mov ebx, MSG_PROT_MODE
call print_string_pm
call KERNEL_OFFSET
jmp $

BOOT_DRIVE  db 0      
MSG_REAL_MODE   db "Started in 16-Bit Real Mode", 0
MSG_PROT_MODE   db "Successfully switched to 32-Bit Protected Mode", 0 
MSG_LOAD_KERNEL db "Loading Kernel into memory", 0  

times 510 - ($ - $$) db 0

dw 0xaa55

所有消息都正确显示,但 Kernel_entry.asm 中的最后一条消息显示为三个奇怪的字符。我不明白发生了什么。

最佳答案

您需要做的第一件事是更改函数的名称。如果您将其称为 main,则 GCC 的 MinGW 版本将插入对 __main 的调用以进行初始化。例如:

start() {
   char *video_memory = 0xb8000;
   *video_memory = 'X';
}

这意味着您还必须相应地编辑 kernel_entry.asm:

[bits 32]
[extern _start]
call _start
jmp $ 

接下来像以前一样编译和组装这两个文件,并用这些命令链接它:

ld -T NUL -o kernel.tmp -Ttext 0x1000 kernel_entry.o kernel.o
objcopy -O binary -j .text  kernel.tmp kernel.bin 

第一个命令将对象链接为 PECOFF 可执行文件,然后第二个命令将其转换为二进制文件。现在将二进制文件与引导加载程序结合起来:

copy /b boot_sect.bin+kernel.bin os-image

关于c - ld: cannot perform PE operations on non PE output file 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25128579/

相关文章:

c - 数组2D到1D的转换和混淆

c++ - 堆栈展开真的需要锁吗?

c++ - std::thread 在 cygwin 中有效,但在 MinGw 中无效

c++ - 如何有条件地为 Eclipse 中的交叉编译项目包含两个相同版本的不同名称的库?

c++ - 为什么 gcc 的右移代码在 C 和 C++ 模式下不同?

C对日志文件的多次写访问(linux env)

c++ - 如何将 C++ 或 C 中的字符串转换为整数数组?

c++ - GCC 中友元函数的范围

c++ - 我可以在 MacOS X 10.11 上让 gcc/g++ 指向 ACTUAL gcc/g++ 吗?

boost - 使用 MinGW 构建 Boost 1.52