Search code examples
cassemblynasmld

Linking error when using ld to link object files into a binary


I was following an os tutorial. I could compile the code successfully but encountered an issue while linking the object files binaries.

ld: error: loader.o:1:1: invalid character

Here is my code for your reference:

Loader in nasm

; Loader.asm
bits 32
extern _main
global start

start:
call _main  ; Call our kernel's main() function
cli        ; Stop interrupts (thats another article?)
hlt        ; Stop all instructions

My C code

//main.c
int main( void )
{
  puts("Hello, world!"); /* Print our welcome message */
 for(;;); /* Keep the OS running */
}


/* video.c */
int x, y; /* Our global 'x' and 'y' */
char color; /* Our global color attribute */
void putc( unsigned char c )
{
    char *vidmem = (char*)0xB8000; /* pointer to video memory */
    int pos = ( y * 2 ) + x; /* Get the position */
    vidmem[pos]   = c; /* print the character */
    vidmem[pos++] = color; /* Set the color attribute */
    if (c == '\n') // newline
    {
        y++;
        x = 0;
    }
    else
        x += 2; // 2 bytes per char
}

int puts( char *message )
{
    int length;
    while(*message)
    {
        putc(*message++);
        length++;
    }
return length;
}

I compiled these by running:

gcc -ffreestanding -fno-builtin -nostdlib -c *.c    // (that's main.c and video.c)
nasm -f aout loader.asm -o loader.o

Solution

  • You should ask nasm to create elf output, not aout. That is, use -f elf.