1

I'm trying to make a simple OS, so I wrote a small kernel that consist out of a c file an assembly file that calls the main function in the c file.
but when I try to compile and link the two files together I get a file format not recognized error by the linker.

this is my Makefile:

BUILD?=build/
ASM?=nasm
ASMFLAGS?=-f obj
CC=i386-elf-gcc
LD=i386-elf-ld
CCFLAGS=-m32 -std=c11 -O2 -g -Wall -Wextra -Wpedantic -Wstrict-aliasing
CCFLAGS+=-Wno-pointer-arith -Wno-unused-parameter
CCFLAGS+=-nostdlib -nostdinc -ffreestanding -fno-pie -fno-stack-protector
CCFLAGS+=-fno-builtin-function -fno-builtin
LDFLAGS=

SOURCES_C=$(wildcard *.c)
SOURCES_ASM=$(wildcard *.asm)
OBJECTS_C=$(patsubst %.c,$(BUILD)/kernel/c/%.obj,$(SOURCES_C))
OBJECTS_ASM=$(patsubst %.asm,$(BUILD)/kernel/asm/%.obj,$(SOURCES_ASM))

all: kernel.bin

kernel.bin: $(OBJECTS_ASM) $(OBJECTS_C)
    $(LD) -o $(BUILD)/kernel.bin $< $(LDFLAGS) -Tlink.ld    

$(BUILD)/kernel/c/%.obj: %.c always
    $(CC) $(CCFLAGS) -o $@ $<

$(BUILD)/kernel/asm/%.obj: %.asm always
    $(ASM) $(ASMFLAGS) -o $@ $<

always:
    mkdir -p $(BUILD)/kernel/c
    mkdir -p $(BUILD)/kernel/asm

I also tried to change the -f flag in nasm to elf, but the I get a undefined reference to main error.

Here is my assembly file calling main:

[bits    32]
[extern main]

section .text
global _start
_start:
    call main

And my C file with the main function:

void main(){
    volatile char* video_memory = (volatile char*)0xb800;
    *video_memory = 'X';
}

So does anyone have an idea on what is causing the problem?

3
  • 2
    Using -f elf32 with NASM would be correct here since the default is to use -f bin which the linker can't handle thus the error. Undefined reference to main - can you show us you ASM file? Is main being called from your assembly code? If it is, do you have a main defined in your C files? Commented Jun 25, 2023 at 16:52
  • 1
    What I didn't notice before is that your compiler flags CCFLAGS is missing -c. Without -c you are compiling each C file to an executable and then linking the executables to a binary. Use -c to compile to actual object files. Commented Jun 25, 2023 at 19:08
  • 1
    yes, I thought that I did something wrong building my cross compiler, so I built it again and it took some time. But it turns out it was the -c flag in gcc. Thank you so much! Commented Jun 26, 2023 at 20:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.