Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How does one do this?

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

like image 735
Doug T. Avatar asked Sep 26 '08 00:09

Doug T.


People also ask

Does gcc compile to assembly?

Programmers can write their own assembly code by hand and compile it with gcc into a binary executable program. For example, to implement a function in assembly, add code to a . s file and use gcc to compile it.

How can I see gcc output?

The gcc provides a great feature to get all intermediate outputs from a source code while executing. To get the assembler output we can use the option '-S' for the gcc. This option shows the output after compiling, but before sending to the assembler. The syntax of this command is like below.

How is C compiled to assembly?

The compiler takes the preprocessed file and uses it to generate corresponding assembly code. Assembly code, or assembly language (often abbreviated asm), is a high-level programming language that corresponds programming code with the given architecture's machine code instructions.

Can gcc translate C code to object code?

GCC in capitals is the abbreviation for the GNU Compiler Collection and it supports languages like C and C++. Now in all lower case, it is the GNU C Compiler. It will compile your C code making it object code, also called machine code.


1 Answers

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.

like image 65
Andrew Edgecombe Avatar answered Sep 26 '22 02:09

Andrew Edgecombe