使用ld链接时,未定义引用’__main’
/* test.c */ void func1() { } int main() { func1(); }
您好,我正在使用C编写内核代码。但是我测试了上面的代码以了解如何构建C内核代码。 下面的命令就是我给出的提示。 我在Windows 8.1上使用MinGW。
gcc -c -m32 test.c ld -o test -Ttext 0x00 -e _main test.o
但这个错误是从ld发生的。
test.o:test.c:(.text+0x7): undefined reference to `__main'
所以,我尝试了不同的方式。 为gcc添加-nostdlib和–freestanding选项。 但结果是一样的。 CRT0中是__main函数吗? 我该怎么做才能解决这个问题..?
如果您真正进入操作系统开发,唯一可行的方法是使用类似Unix的操作系统,如GNU / Linux或Mac OS X.
以下两个是必须的:
-ffreestanding -nostdlib -lgcc
然后建议使用-Wall
, -Wextra
和-Werror
类的东西,因为内核代码中的错误非常难以调试。
关于入口点,通常使用通过-T linker.ld
传递给ld
的链接 -T linker.ld
。 例如,我的(不要复制粘贴它!)如下所示。 它适用于支持虚拟内存的高半内核 :
ENTRY(__start__) OUTPUT_FORMAT(elf32-i386) SECTIONS { . = 0xC0100000; .text BLOCK(4K) : AT(ADDR(.text) - 0xC0000000) { KEEP(*(.multiboot)) KEEP(*(.boot)) *(.text) } .rodata ALIGN(0x1000) : AT(ADDR(.rodata) - 0xC0000000) { *(.rodata*) } .data ALIGN(0x1000) : AT(ADDR(.data) - 0xC0000000) { *(.data) } .bss : AT(ADDR(.bss) - 0xC0000000) { *(COMMON) *(.bss) *(.stack) } __kend__ = .; }
您可以使用gcc
而不是ld
来执行链接:
gcc -o test test.o -nostdlib -lgcc
-lgcc
选项提供__main
函数。