Assembler and Inline Assembler Code in g++

By | February 7, 2022

My career as software developer began with embedded programming for 8-bit microprocessor. The main language I used in that time was assembler. Processors changed as assembler changed as well. Later when I started develop Windows implementation in C++ I also used inline assembler instructions in my C++ code, sometime it was necessary for example when naked functions were used. Currently Microsoft Visual Studio does not support inline assembler for 64-bit platform. But g++ compiler does. Here is example of such code:


#include <stdio.h>
int main()
{
   long int sum;
   __asm__(
      "movq $0xa, %rax\n"
      "movq $0xd, %rdx\n"
      "addq %rax, %rdx\n");
   __asm__("movq %%rdx, %0\n":"=r" (sum));
   printf("Sum of rax and rdx registers is: %ld\n", sum);
   return 0;
}

# g++ -o asm64 asm64.cpp
# ./asm64
Sum of rax and rdx registers is: 23

The same code without C++ wrapper:


   .global main
   .text
main:
   movq  $0xa, %rax
   movq  $0xd, %rdx
   addq  %rax, %rdx
   push  %rax            # save registers
   push  %rcx
   # printf(format, sum)
   movq  $format, %rdi   # format parameter (format)
   movq  %rdx, %rsi      # 2-nd parameter – sum
   xorq  %rax, %rax      # printf is var args
   call  printf
   pop   %rcx            # restore caller-save register
   pop   %rax
   # exit(0)
   movq  $60, %rax       # syscall 60 is exit
   xorq  %rdi, %rdi      # return code 0
   syscall
format:
   .asciz "Sum of rax and rdx registers is: %ld\n"

# g++ att.s -o att
# ./att
Sum of rax and rdx registers is: 23

Leave a Reply

Your email address will not be published. Required fields are marked *