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.
In this example, it can be seen that through the Assembly code:
3
to register eax
ebx
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.