【发布时间】:2021-01-14 07:07:43
【问题描述】:
所以我正在尝试将 C 文件编译为 .bin,然后在我的第一阶段引导加载程序之后将其添加到 .img 文件中。
我在answer 用户Michael Petch 中找到了这些 bash 命令:
gcc -g -m32 -c -ffreestanding -o kernel.o kernel.c -lgcc
ld -melf_i386 -Tlinker.ld -nostdlib --nmagic -o kernel.elf kernel.o
objcopy -O binary kernel.elf kernel.bin
并使用了这个 C 代码(取自相同的答案,保存为 kernel.c):
/* This code will be placed at the beginning of the object by the linker script */
__asm__ ("jmp _main\r\n");
int main(){
/* Do Stuff Here*/
return 0; /* return back to bootloader */
}
我在 cygwin 中执行了这些命令,结果如下:
ld: kernel.o: in function `main':
/cygdrive/d/Work/asm/kernel.c:4: undefined reference to `___main'
objcopy: 'kernel.elf': No such file
linker.ld 文件在这里:
OUTPUT_FORMAT(elf32-i386)
ENTRY(_main)
SECTIONS
{
. = 0x9000;
.text : { *(.text.start) *(.text) }
.data : { *(.data) }
.bss : { *(.bss) *(COMMON) }
}
我已经使用objdump 对 kernel.o 文件进行了反汇编,结果如下:
> objdump -d -j .text kernel.o
kernel.o: file format pe-i386
Disassembly of section .text:
00000000 <.text>:
0: eb 00 jmp 2 <_main>
00000002 <_main>:
2: 55 push %ebp
3: 89 e5 mov %esp,%ebp
5: 83 e4 f0 and $0xfffffff0,%esp
8: e8 00 00 00 00 call d <_main+0xb>
d: b8 00 00 00 00 mov $0x0,%eax
12: c9 leave
13: c3 ret
这是gcc -v 的结果,如果这也有帮助的话:
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-cygwin/10/lto-wrapper.exe
Target: x86_64-pc-cygwin
Configured with: /mnt/share/cygpkgs/gcc/gcc.x86_64/src/gcc-10.2.0/configure --srcdir=/mnt/share/cygpkgs/gcc/gcc.x86_64/src/gcc-10.2.0 --prefix=/usr --exec-prefix=/usr --localstatedir=/var --sysconfdir=/etc --docdir=/usr/share/doc/gcc --htmldir=/usr/share/doc/gcc/html -C --build=x86_64-pc-cygwin --host=x86_64-pc-cygwin --target=x86_64-pc-cygwin --without-libiconv-prefix --without-libintl-prefix --libexecdir=/usr/lib --with-gcc-major-version-only --enable-shared --enable-shared-libgcc --enable-static --enable-version-specific-runtime-libs --enable-bootstrap --enable-__cxa_atexit --with-dwarf2 --with-tune=generic --enable-languages=c,c++,fortran,lto,objc,obj-c++ --enable-graphite --enable-threads=posix --enable-libatomic --enable-libgomp --enable-libquadmath --enable-libquadmath-support --disable-libssp --enable-libada --disable-symvers --with-gnu-ld --with-gnu-as --with-cloog-include=/usr/include/cloog-isl --without-libiconv-prefix --without-libintl-prefix --with-system-zlib --enable-linker-build-id --with-default-libstdcxx-abi=gcc4-compatible --enable-libstdcxx-filesystem-ts
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 10.2.0 (GCC)
我做错了什么?这是由cygwin引起的吗?如果是,我可以在 Windows 上使用其他选项吗? (我尝试过 MSVC,但这太可怕了)
另外,我的引导加载程序没有使用任何.section 伪操作(我不知道如何正确使用它们),这是否会在未来引起任何问题,它是否可以在编译后的 C 程序中正常工作?
【问题讨论】:
-
因为您选择不使用交叉编译器,所以您必须处理 Windows 命名约定的细微差别和其他奇怪的问题。这适用于 Cygwin 和 MinGW 的本机 Windows 编译器。我的理解是,使用 CygWin 它会寻找一个名为
___main的入口点。您可能希望使用main以外的其他内容来避免这种情况。尝试使用kmain,因为我相信编译器会在main中生成代码来调用___main -
@MichaelPetch 谢谢,您的理解确实是正确的,将main方法重命名为
__main并适当设置跳转指令和linker.ld文件后,LD继续正确创建elf文件,请将此作为答案发布,以便我可以关闭问题。