c++nasm

From C/C++ to NASM src


I need to develope some algorithms that are really easy to do with a hig level language as C or C++, but become really hard to write directly as NASM istructions.

Since basically a C and C++ compiler have to use low level istructions to produce binaries, is there a simple way to obtain the NASM code from C\C++ programs.


Solution

  • From man gcc:

    -S

    Stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler input file specified.

    By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.

    gcc -S hello.c should create file hello.s with corresponding assembler code.

    Works for g++ too. Other compilers probably have similar option.


    For example, for this program (hello.c):

    #include <stdio.h>
    
    int main() {
        printf("Hello, world! %d\n", 6*7);
        return 0;
    }
    

    The output (hello.s) contains this:

            .file   "hello.c"
            .section        .rodata
    .LC0:
            .string "Hello, world! %d\n"
            .text
            .globl  main
            .type   main, @function
    main:
    .LFB0:
            .cfi_startproc
            pushq   %rbp
            .cfi_def_cfa_offset 16
            .cfi_offset 6, -16
            movq    %rsp, %rbp
            .cfi_def_cfa_register 6
            movl    $42, %esi
            movl    $.LC0, %edi
            movl    $0, %eax
            call    printf
            movl    $0, %eax
            popq    %rbp
            .cfi_def_cfa 7, 8
            ret
            .cfi_endproc
    .LFE0:
            .size   main, .-main
            .ident  "GCC: (Debian 4.7.2-5) 4.7.2"
            .section        .note.GNU-stack,"",@progbits