Convert C/C++ code to assembly language

Assembly language is a low-level programming language that provides a human-readable representation of machine code. The GNU Compiler Collection (GCC) allows us to convert C/C++ source code into assembly language for analysis and optimization purposes.

Syntax

gcc -S source_file.c
gcc -S source_file.cpp

Note: To use gcc, you need to install it on your system. On Ubuntu/Debian: sudo apt install gcc, on Windows: install MinGW or use WSL.

Parameters

  • -S − Generate assembly code and stop before assembling
  • source_file − The C/C++ source file to convert

Example: Simple C Program

Let's demonstrate assembly generation with a simple C program that adds two numbers −

#include <stdio.h>

int main() {
    int x = 50;
    int y = 60;
    int sum = x + y;
    printf("Sum is: %d\n", sum);
    return 0;
}
Sum is: 110

Generated Assembly Output

When we compile the above C program using gcc -S program.c, it generates the following assembly code −

.file   "program.c"
.text
.section    .rodata
.LC0:
    .string "Sum is: %d\n"
.text
.globl  main
.type   main, @function
main:
.LFB0:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $16, %rsp
    movl    $50, -12(%rbp)
    movl    $60, -8(%rbp)
    movl    -12(%rbp), %edx
    movl    -8(%rbp), %eax
    addl    %edx, %eax
    movl    %eax, -4(%rbp)
    movl    -4(%rbp), %eax
    movl    %eax, %esi
    leaq    .LC0(%rip), %rdi
    movl    $0, %eax
    call    printf@PLT
    movl    $0, %eax
    leave
    ret
.LFE0:
    .size   main, .-main

Key Assembly Instructions

  • movl − Move 32-bit data between registers or memory
  • addl − Add two 32-bit values
  • pushq/popq − Push/pop 64-bit values to/from stack
  • call − Call a function (printf in this case)
  • ret − Return from function

How It Works

  1. The compiler translates C variables into stack memory locations
  2. Constants (50, 60) are moved directly into memory
  3. The addition operation uses CPU registers (%eax, %edx)
  4. Function calls follow the calling convention for parameter passing

Conclusion

Converting C code to assembly using gcc's -S option helps understand low-level program execution. This is valuable for performance optimization and debugging complex programs.

Updated on: 2026-03-15T10:29:24+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements