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.
I would like to add to these answers that if you give gcc the flag
-fverbose-asm
, the assembler it emits will be a lot clearer to read.If you compile with debug symbols, you can use
objdump
to produce a more readable disassembly.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
Example:
You can use gdb for this like objdump.
This excerpt is taken from http://sources.redhat.com/gdb/current/onlinedocs/gdb_9.html#SEC64
Here is an example showing mixed source+assembly for Intel x86:
Using the
-S
switch to GCC on x86 based systems produces a dump of AT&T syntax, by default, which can be specified with the-masm=att
switch, like so:Whereas if you'd like to produce a dump in Intel syntax, you could use the
-masm=intel
switch, like so:(Both produce dumps of
code.c
into their various syntax, into the filecode.s
respectively)In order to produce similar effects with objdump, you'd want to use the
--disassembler-options=
intel
/att
switch, an example (with code dumps to illustrate the differences in syntax):and
Ripped straight from http://www.delorie.com/djgpp/v2faq/faq8_20.html (but removing erroneous
-c
)Did you try
gcc -S -fverbose-asm -O source.c
then look into the generatedsource.s
assembler file ?The generated assembler code goes into
source.s
(you could override that with-o
assembler-filename ); the-fverbose-asm
option asks the compiler to emit some assembler comments "explaining" the generated assembler code. The-O
option asks the compiler to optimize a bit (it could optimize more with-O2
or-O3
).If you want to understand what
gcc
is doing try passing-fdump-tree-all
but be cautious: you'll get hundreds of dump files.BTW, GCC is extensible thru plugins or with MELT (a high level domain specific language to extend GCC).