How to Run Assembly within C++ code

A useful resource for extreme situations.


How to Run Assembly within C++ code


C++ is a comprehensive and powerful programming language, but there are few highly specialized situations that it cannot solve.

For these situations, C++ offers an option that allows you to discard Assembly code at any time. time.

This option is to use the __asm__() instruction or just asm(). In other words, the Assembly language can be incorporated directly into the C++ program.


Basic example of use

In this example, it can be seen that through the Assembly code:

  • Moves immediate value 3 to register eax
  • Move immediate value 6 to register ebx
  • The added value is stored in sum for output

asm.cpp

#include <iostream>

int main() {
   int sum;
   __asm__ ( "movl $3, %%eax;"
       "movl $6, %%ebx;"
       "addl %%ebx, %%eax ":"=a"(sum));
   std::cout << sum << '\n';
   return 0;
}

After compiling and running:

g++ asm.cpp
./a.out

The output will be the sum: 9.

If you want to avoid using underlines it will work the same way:

#include <iostream>

int main() {
   int sum;
   asm("movl $3, %%eax;"
       "movl $6, %%ebx;"
       "addl %%ebx, %%eax ":"=a"(sum));
   std::cout << sum << '\n';
   return 0;
}

The fact of using __asm__ like this is that the programmer has greater control of the native resources of C++.

For more information visit: https://en.cppreference.com/w/cpp/language/asm.


cpp assembly


Share


YouTube channel

Subscribe


Marcos Oliveira

Marcos Oliveira

Software developer
https://github.com/terroo

Related articles