Search code examples
cgccbinaryfilesld

How do I produce plain binary from object files?


How should I produce raw binary file from two object (.o) files?

I want the plain binary format produced by nasm -f bin when compiling a .asm file, but for .o files.

By a plain binary, I mean a file which contains only the instructions, not some extra information, as many executable files contain a lot of extra helpful information.

See http://www.nasm.us/doc/nasmdoc7.html for information on that.

PS: I want to make a "plain binary" to start in QEMU.


Solution

  • This brings back memories. I'm sure there is a better way to do this with linker scripts, but this is how I did it when I was young and stupid:

    # compile some files
    gcc -c -nostdlib -nostartfiles -nodefaultlibs -fno-builtin kernel.c -o kernel.o
    gcc -c -nostdlib -nostartfiles -nodefaultlibs -fno-builtin io.c -o io.o
    
    # link files and place code at known address so we can jump there from asm
    ld -Ttext 0x100000 kernel.o io.o -o kernel.out
    
    # get a flat binary
    objcopy -S -O binary kernel.out kernel.bin
    

    The file kernel.c started with

    __asm__("call _kmain");
    __asm__("ret");
    
    void kmain(void) { ... }
    

    The fun part is writing the loader in assembler.