How do I create a simple binary from object files?

How can I create a source binary from two files (.o)?

I want a simple binary format generated nasm -f bin

when compiling an .asm file, but for .o files.

In simple binary form, I mean a file that only contains instructions and not some additional information, as many executables contain a lot of additional useful information.

For information on this see http://www.nasm.us/doc/nasmdoc7.html .

PS: I want to do "regular binary" to start in QEMU .

+3


source to share


2 answers


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

# 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

      

File kernel.c

started with



__asm__("call _kmain");
__asm__("ret");

void kmain(void) { ... }

      

The interesting part is writing the bootloader to assembler.

+6


source


ld --oformat binary

- a more direct option:

ld --oformat binary -o main.img -Ttext 0x7C00 main.o

      

The downside to this method is that I don't think it is possible to reuse symbols for debugging, since we need something like:

qemu-system-i386 -hda main.img -S -s &
gdb main.elf -ex 'target remote localhost:1234'

      

So in this case you have to stick with objcopy

. See also: fooobar.com/questions/322017 / ...



Also make sure you are using your own clean script linker: fooobar.com/questions/322016 / ...

A repository with working examples for some common cases:

A similar question: How do I create simple binaries like nasm -f bin with GNU GAS assembler?

+1


source







All Articles