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.
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 tells ld to generate a binary file. This removes the need to objcopy separately.
A Raw Binary File contains the binary equivalent of a Tabular Text File (. ttf). You can also generate Raw Binary Files with the makeprogfile utility, or from previously generated SRAM Object Files (. sof) or Partial Mask SRAM Object Files (.
To open the Binary Editor on an existing file, go to menu File > Open > File, select the file you want to edit, then select the drop arrow next to the Open button, and choose Open With > Binary Editor.
GCC stands for GNU Compiler Collections which is used to compile mainly C and C++ language. It can also be used to compile Objective C and Objective C++.
Try this out:
$ gcc -c test.c $ objcopy -O binary -j .text test.o binfile
You can make sure it's correct with objdump
:
$ objdump -d test.o test.o: file format pe-i386 Disassembly of section .text: 00000000 <_f>: 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 ec 04 sub $0x4,%esp 6: 8b 45 08 mov 0x8(%ebp),%eax 9: 0f af 45 08 imul 0x8(%ebp),%eax d: 89 45 fc mov %eax,-0x4(%ebp) 10: 8b 45 fc mov -0x4(%ebp),%eax 13: 83 c0 02 add $0x2,%eax 16: c9 leave 17: c3 ret
And compare it with the binary file:
$ hexdump -C binfile 00000000 55 89 e5 83 ec 04 8b 45 08 0f af 45 08 89 45 fc |U......E...E..E.| 00000010 8b 45 fc 83 c0 02 c9 c3 |.E......| 00000018
You can pass options to the linker directly with -Wl,<linker option>
The relevant documentation is copied below from the man gcc
-Wl,option
Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. You can use this syntax to pass an argument to the option. For example, -Wl,-Map,output.map passes -Map output.map to the linker. When using the GNU linker, you can also get the same effect with -Wl,-Map=output.map.
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
tells ld
to generate a binary file.
This removes the need to objcopy
separately.
Note that --oformat=binary
can be expressed as OUTPUT_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With