Panther Coder
Panther Coder

Reputation: 1078

Linking a file using ld to output a binary file gives error in OS development

I am learning Operating system tutorials. I created 2 files.

  1. boot.asm
  2. kernel.c

The kernel.c is as follows :

int main()
{
  char *src = (char *)0xB8000000L;
  *src = 'M';
  src += 2;
  *src = 'D';
  return 0;
}

The kernel is used to write a character to the text mode video display area. The kernel was compiled using Windows version of GCC with:

gcc -ffreestanding -c -m16 kernel.c -o kernel.o

I link the kernel object to a binary file using LD:

ld -Ttext 0x10000 --oformat binary -o kernel.bin kernel.o

The error I get is:

ld : cannot link the file which is not PE executable type

Can anybody solve this error?

Upvotes: 3

Views: 6193

Answers (2)

Michael Petch
Michael Petch

Reputation: 47603

Your Windows version of LD likely doesn't support anything more than windows PE types. One way around this is to output to PE and then use objcopy to convert from the PE file to binary.

For this to work you will have to rename main to _main. With -ffreestanding GCC will emit an object without the Windows ABI convention of prepending a leading underscore to non-static functions. We'll be using your LD to output a Windows PE file first and it will complain about __main entry point not being defined. To get around this you rename main to _main so the linker doesn't complain.

Use these instructions for generating the kernel binary:

gcc -ffreestanding -c -m16 kernel.c -o kernel.o
ld -Ttext 0x10000 -o kernel.pe kernel.o
objcopy -O binary kernel.pe kernel.bin

The LD command outputs to a file called kernel.pe. objcopy converts kernel.pe to binary with -O binary outputting to kernel.bin

Upvotes: 4

Serge
Serge

Reputation: 6095

This means that ld itself is not configured at its compile time to support output formats other than PE, Portable Executable - the native Windows executable file format.

Find the one that supports or build it yourself.

Upvotes: 1

Related Questions