开发简易内核时出现undefined reference to `kernel_main'错误的解决求助
kernel_main" When Building a Kernel on Windows (No Linux VM Needed) Hey, I've dealt with this exact linker error while tinkering with kernel development on Windows using MinGW—let's break down the root cause and fix it step by step:
1. The Core Issue: Name Mangling in 32-bit C Compilation
On 32-bit MinGW GCC (the Windows port of GCC), C function names get an underscore prefix added during compilation. Your kernel_main() function actually gets compiled to a symbol named _kernel_main, but your assembly code is looking for kernel_main—that's why the linker can't find it.
Fix the Assembly Code (boot.asm)
Update your extern declaration and function call to use the underscore-prefixed name:
global loader extern _kernel_main ; Add underscore here MAGIC equ 0xbad FLAGS equ 0x3 CHECKSUM equ -(MAGIC+FLAGS) section .text align 4 dd MAGIC dd FLAGS dd CHECKSUM loader: call _kernel_main ; Also update the call here cli quit: hlt jmp quit
2. Make Sure You're Using the Right 32-bit Toolchain
You'll need a proper 32-bit MinGW-w64 toolchain (not the old, deprecated MinGW):
- Download an i686 (32-bit) version of MinGW-w64, install it, and add its
bindirectory to your system PATH. - Ensure you have a recent version of NASM that supports the
-f elf32flag.
3. Fix Up Your Compilation & Linking Commands
Your original commands had a couple of small issues—here's the corrected version:
Compile the C Kernel
gcc -m32 -c kernel.c -o kernel.o -nostdlib -nostartfiles -nodefaultlibs -ffreestanding
-c: Tells GCC to only compile (not link), which is what we want for generating an object file.-ffreestanding: Critical for kernel development—this tells GCC we're building for an environment without standard library support.
Compile the Assembly Bootloader
nasm -f elf32 -o boot.o boot.asm
This part was already correct—keep it as is.
Link the Object Files
ld -m elf_i386 -T linker.ld -o final.bin boot.o kernel.o
-m elf_i386: Specifies we're targeting 32-bit ELF objects—your original command used-elf_i386which is invalid syntax.
4. Test Your Kernel (Optional)
If you want to verify it works, grab QEMU for Windows and run:
qemu-system-i386 -kernel final.bin
You should see your silly (but cute) cat message printed to the QEMU screen!
内容的提问来源于stack exchange,提问作者Leocat

