I was wondering how to use GCC on my C source file to dump a mnemonic version of the machine code so I could see what my code was being compiled into. You can do this with Java but I haven't been able to find a way with GCC.
I am trying to re-write a C method in assembly and seeing how GCC does it would be a big help.
Best Answer
If you compile with debug symbols (add
-g
to your GCC command line, even if you're also using-O3
1), you can useobjdump -S
to produce a more readable disassembly interleaved with C source.objdump -drwC -Mintel
is nice:-r
shows symbol names on relocations (so you'd seeputs
in thecall
instruction below)-R
shows dynamic-linking relocations / symbol names (useful on shared libraries)-C
demangles C++ symbol names-w
is "wide" mode: it doesn't line-wrap the machine-code bytes-Mintel
: use GAS/binutils MASM-like.intel_syntax noprefix
syntax instead of AT&T-S
: interleave source lines with disassembly.You could put something like
alias disas="objdump -drwCS -Mintel"
in your~/.bashrc
. If not on x86, or if you like AT&T syntax, omit-Mintel
.Example:
Note that this isn't using
-r
so thecall rel32=-4
isn't annotated with theputs
symbol name. And looks like a brokencall
that jumps into the middle of the call instruction in main. Remember that therel32
displacement in the call encoding is just a placeholder until the linker fills in a real offset (to a PLT stub in this case, unless you statically link libc).Footnote 1: Interleaving source can be messy and not very helpful in optimized builds; for that, consider https://godbolt.org/ or other ways of visualizing which instructions go with which source lines. In optimized code there's not always a single source line that accounts for an instruction but the debug info will pick one source line for each asm instruction.