How can I see the assembly code that is generated by a gcc (any flavor) compiler for a C/C++ program?

28,253

Solution 1

Add -S switch to your command line.

Edit: Do not forget that it will place the assembly to the files you specified under -o switch.

Solution 2

How to restrict it to a specific function or a code block?

Put that function in a separate source file (and use a different command-line parameter for that one source file).

Solution 3

You could also run that program in a debugger like gdb and use a disassembly view. In gdb you could use the command disass/m to view the assembly mixed with the C code on the current location.

Solution 4

You could stop you program at a breakpoint in the Visual Studio debugger and do "show assembly" and even step through it one instruction at a time.

Share:
28,253
vehomzzz
Author by

vehomzzz

He adapts a lazy approach to a complex learning. His eclectic personality coupled with eccentric character caused much harm to masses, and to himself.

Updated on February 28, 2020

Comments

  • vehomzzz
    vehomzzz over 4 years

    I am trying to optimize a lot of multiplications and pointer arithmetics and would like to see what the compiler does underneath when I put in optimization flags.

    --Edit--

    How to restrict it to a specific function or a code block?

    --Edit_2--

    How to let gcc generate a less verbose assembly-code?

  • vehomzzz
    vehomzzz almost 15 years
    That's what I have been doing. I am curious if it's possible from just options.
  • aaronsnoswell
    aaronsnoswell over 10 years
    Why was this response down-voted? It is a perfectly valid response.
  • CodeClown42
    CodeClown42 over 9 years
    @aaronsnoswell I didn't do it, but presumably because the question is explicitly about GCC.
  • Clément
    Clément about 8 years
    Can you add a minimal example? disass/m just prints No frame selected.
  • Peter Cordes
    Peter Cordes over 6 years
    You can use gcc -O3 -march=native foo.c -S -o- | less to pipe into less instead of creating a .s file. See also How to remove “noise” from GCC/clang assembly output? for more tips about seeing the "interesting part" of the asm output, especially Matt Godbolt's CppCon2017 talk: “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid”
  • Peter Cordes
    Peter Cordes over 6 years
    This may not reflect how it's really optimized if it can inline into callers. (Especially with link-time optimization). Having even one parameter be a compile-time constant can make a big difference, or having the alignment or size of an array known can change auto-vectorization a lot. But yes, this is good if you understand what you're doing.