2
votes

I cannot combine my kernel_entry.asm and main.c. My main.c calls an asm function Sum. Both nasm and gcc compiles respective files. However, the linker gives an error.

Kernel_entry.asm:

[bits 32]
[extern _start]
[global _Sum]

....

_Sum:
    push    ebp             
    mov     ebp, esp
    mov     eax, [ebp+8]    
    mov     ecx, [ebp+12]   
    add     eax, ecx        
    pop     ebp             
    ret 

main.c:

....
extern int Sum();

void start() {
    ....
    int x = Sum(4, 5);
    ....
}

To compile source files, I use following commands:

nasm kernel_entry.asm -f win32 -o kernel_entry.o
gcc -ffreestanding -c main.c -o main.o
....
ld -T NUL -o kernel.tmp -Ttext 0x1000 kernel_entry.o main.o mem.o port_in_out.o screen.o idt.o

Linker gives following error:main.o:main.c:(.text+0xa82): undifened reference to 'Sum'. I tried everything but couldn't find any solution. When I remove asm function call from main.c, it works.

1
Thank you but gcc -m32 did not work for me. I am working on a Windows computer. Maybe that is the reason?user2972185
Using nasm kernel_entry.asm -f elf -o kernel_entry.o did it for merfernandes
@rfernandes you should write answer from your comments.Jeegar Patel
@Mr.32 Thanks for reminding me, donerfernandes

1 Answers

2
votes

The TL;DR version of the answer is that mixing nasm's -f win32 generates an object file that is not compatible with the GNU toolchain on Windows - you need to use -f elf if you want to link using ld. That is described in NASM's documentation here under sections 7.5 and 7.9.

The hint for me was that by running nm kernel_entry.o generated:

00000000 a .absolut
00000000 t .text
00000001 a @feat.00
         U _start
         U _Sum

Which basically shows Sum as an undefined symbol. After compiling as ELF, I got:

         U _start
00000000 T _Sum

indicating Sum as a recognised symbol in the text section.