i386 GNU ld:文件无法识别:无法识别文件格式

时间:2017-10-06 23:17:30

标签: c gcc makefile linker osdev

我正在通过The Little Book About OS Development,特别是关于帧缓冲区(链接)的部分。我能够成功组装,链接,转换成ISO文件并启动纯组件,但是一旦我尝试链接编译的目标文件以获取我的C代码(从我的加载器调用,它是用汇编编写的) ,链接器抱怨。这是输出:

nasm -f elf loader.s -o loader.o
nasm -f elf out.s -o out.o
/usr/local/Cellar/gcc@6/6.4.0/bin/gcc-6 -m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector -nostartfiles -nodefaultlibs -Wall -Wextra -Werror -c  framebuffer.c -o framebuffer.o
/usr/local/Cellar/gcc@6/6.4.0/bin/gcc-6 -m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector -nostartfiles -nodefaultlibs -Wall -Wextra -Werror -c  kmain.c -o kmain.o
i386-unknown-linux-gnu-ld -T link.ld -melf_i386 loader.o out.o framebuffer.o kmain.o -o kernel.elf
framebuffer.o: file not recognized: File format not recognized
make: *** [kernel.elf] Error 1

我在Mac上,因为您可以告诉我已经编译了GNU链接器的自定义版本,以便我可以使用链接器脚本,并且我已确保指定GCC 6 (系统默认为4.0)。无论如何,这是我的Makefile:

OBJECTS = loader.o out.o framebuffer.o kmain.o
CC = /usr/local/Cellar/gcc@6/6.4.0/bin/gcc-6
CFLAGS = -m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector \
-nostartfiles -nodefaultlibs -Wall -Wextra -Werror -c
LDFLAGS = -T link.ld -melf_i386
AS = nasm
ASFLAGS = -f elf

all: kernel.elf

kernel.elf: $(OBJECTS)
    i386-unknown-linux-gnu-ld $(LDFLAGS) $(OBJECTS) -o kernel.elf

os.iso: kernel.elf
    cp kernel.elf iso/boot/kernel.elf
    mkisofs -R                          \
        -b boot/grub/stage2_eltorito    \
        -no-emul-boot                   \
        -boot-load-size 4               \
        -A os                           \
        -input-charset utf8             \
        -quiet                          \
        -boot-info-table                \
        -o os.iso                       \
        iso

run: os.iso
    bochs -f bochsrc.txt -q

%.o: %.c
    $(CC) $(CFLAGS)  $< -o $@

%.o: %.s
    $(AS) $(ASFLAGS) $< -o $@

clean:
    rm -rf *.o kernel.elf os.iso

这是我的链接器脚本:

ENTRY(loader)                /* the name of the entry label */

SECTIONS {
. = 0x00100000;          /* the code should be loaded at 1 MB */

.text ALIGN (0x1000) :   /* align at 4 KB */
{
*(.text)             /* all text sections from all files */
}

.rodata ALIGN (0x1000) : /* align at 4 KB */
{
*(.rodata*)          /* all read-only data sections from all files */
}

.data ALIGN (0x1000) :   /* align at 4 KB */
{
*(.data)             /* all data sections from all files */
}

.bss ALIGN (0x1000) :    /* align at 4 KB */
{
*(COMMON)            /* all COMMON sections from all files */
*(.bss)              /* all bss sections from all files */
}
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

事实证明,这是通过在我的Mac上交叉编译GNU Binutils和GCC(使用相同的前缀)来解决的。我按照here的说明做了这个。