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 J
If you give GCC the flag -fverbose-asm
, it will
Put extra commentary information in the generated assembly code to make it more readable.
[...] The added comments include:
- information on the compiler version and command-line options,
- the source code lines associated with the assembly instructions, in the form FILENAME:LINENUMBER:CONTENT OF LINE,
- hints on which high-level expressions correspond to the various assembly instruction operands.
godbolt is a very useful tool, they list only has C++ compilers but you can use -x c
flag in order to get it treat the code as C. It will then generate an assembly listing for your code side by side and you can use the Colourise
option to generate colored bars to visually indicate which source code maps to the generated assembly. For example the following code:
#include <stdio.h>
void func()
{
printf( "hello world\n" ) ;
}
using the following command line:
-x c -std=c99 -O3
and Colourise
would generate the following:
use -Wa,-adhln as option on gcc or g++ to produce a listing output to stdout.
-Wa,... is for command line options for the assembler part (execute in gcc/g++ after C/++ compilation). It invokes as internally (as.exe in Windows). See
>as --help
as command line to see more help for the assembler tool inside gcc
Did you try gcc -S -fverbose-asm -O source.c
then look into the generated source.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; which I abandoned in 2017)
I haven't given a shot to gcc, but in case of g++. The command below works for me. -g for debug build and -Wa,-adhln is passed to assembler for listing with source code
g++ -g -Wa,-adhln src.cpp
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:
(gdb) disas /m main Dump of assembler code for function main: 5 { 0x08048330 : push %ebp 0x08048331 : mov %esp,%ebp 0x08048333 : sub $0x8,%esp 0x08048336 : and $0xfffffff0,%esp 0x08048339 : sub $0x10,%esp 6 printf ("Hello.\n"); 0x0804833c : movl $0x8048440,(%esp) 0x08048343 : call 0x8048284 7 return 0; 8 } 0x08048348 : mov $0x0,%eax 0x0804834d : leave 0x0804834e : ret End of assembler dump.