Is there a set of command-line options that will convince gcc to produce a flat binary file from a self-contained source file? For example, suppose the contents of foo.c are
static int f(int x)
{
int y = x*x;
return y+2;
}
No external references, nothing to export to the linker. I'd like to get a small file with just the machine instructions for this function, without any other decoration. Sort of like a (DOS) .COM file except 32-bit protected mode.
You can pass options to the linker directly with
-Wl,<linker option>
The relevant documentation is copied below from the
man gcc
So when compiling with gcc if you pass
-Wl,--oformat=binary
you will generate a binary file instead of the elf format. Where--oformat=binary
tellsld
to generate a binary file.This removes the need to
objcopy
separately.Note that
--oformat=binary
can be expressed asOUTPUT_FORMAT("binary")
from within a linker script. If you want to deal with flat binaries, there's a big chance that you would benefit from high level of control that linker scripts provide.You can use
objcopy
to pull the text segment out of the .o file or the a.out file.Try this out:
You can make sure it's correct with
objdump
:And compare to the binary file:
The other answers are definitely the way to go. However, I had to specify additional command line arguments to objcopy in order for my output to be as expected. Note that I am developing 32-bit code on a 64-bit machine, hence the
-m32
argument. Also, I like intel assembly syntax better, so you'll see that in the arguments as well.Ok, here's where I had to specify that I specifically only wanted the .text section:
It took me about 2 hours of reading and trying different options before I figured this out. Hopefully this saves someone else that time.