How do you get assembler output from C/C++ source in gcc?


Question

How does one do this?

If I want to analyze how something is getting compiled, how would I get the emitted assembly code?

1
329
5/1/2012 4:17:58 AM

Accepted Answer

Use the -S option to gcc (or g++).

gcc -S helloworld.c

This will run the preprocessor (cpp) over helloworld.c, perform the initial compilation and then stop before the assembler is run.

By default this will output a file helloworld.s. The output file can be still be set by using the -o option.

gcc -S -o my_asm_output.s helloworld.c

Of course this only works if you have the original source. An alternative if you only have the resultant object file is to use objdump, by setting the --disassemble option (or -d for the abbreviated form).

objdump -S --disassemble helloworld > helloworld.dump

This option works best if debugging option is enabled for the object file (-g at compilation time) and the file hasn't been stripped.

Running file helloworld will give you some indication as to the level of detail that you will get by using objdump.

381
10/1/2013 1:33:38 AM

This will generate the asm code with the C code + line numbers interweaved to more easily see what lines generate what code.

# create assembler code:
c++ -S -fverbose-asm -g -O2 test.cc -o test.s
# create asm interlaced with source lines:
as -alhnd test.s > test.lst

Found in Algorithms for programmers, page 3 (which is the overall 15th page of the PDF).


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon