If you're learning how programs are translated into low-level instructions, or just curious about what the C or C++ code looks like at the assembly level, you can easily generate assembly code using gcc or g++ compiler. This knowledge is particularly useful for developers interested in optimization, debugging at the assembly level, or simply gaining a deeper understanding of how things work under the hood. This tutorial shows how to generate assembly code using gcc or g++ compiler.
Create the main.c
file for testing:
#include <stdio.h>
int main() {
printf("Hello world\n");
return 0;
}
1. Basic assembly generation
Run command to generate assembly code:
gcc -S main.c
This command compiles the C source code into an assembly file called main.s
. It stops the compilation process after generating the assembly and skips the linking stage. The same syntax applies for g++ compiler when generating assembly code for C++.
2. Output filename
To specify filename, use the -o
option:
gcc -S main.c -o test.s
This does the same as above, but names the output file test.s
instead of the default name.
3. Comments in assembly
Use the -fverbose-asm
option to include extra comments in the assembly code, making it easier to understand what's going on:
gcc -S -fverbose-asm main.c
4. Intel syntax
By default, gcc or g++ compiler uses AT&T syntax for assembly. Use the -masm=intel
option to switch to Intel syntax:
gcc -S -masm=intel main.c
5. Detailed annotated assembly
Use the -Wa,-adhln
option to generate assembly with mixed source code, machine code, and assembly instructions all in one:
gcc -g -Wa,-adhln main.c > main.s
The -g
option includes debug information.
6. Detailed annotated + verbose assembly
The following command combines all the features: debug info, source interleaving, and verbose comments:
gcc -g -Wa,-adhln -fverbose-asm main.c > main.s
It's one of the most detailed assembly views you can get using gcc or g++ compiler and is great for learning or inspection.
Leave a Comment
Cancel reply