The asm declaration in C++ allows assembly language instructions to be embedded directly within a C++ program. It provides a way to execute processor-specific instructions when standard C++ features are not sufficient.
- Provides direct access to hardware and CPU registers.
- Commonly used in system programming, embedded systems, and performance-critical applications.
Example: Program uses inline assembly to subtract two values and store the result in a C++ variable.
#include <iostream>
using namespace std;
int main()
{
int result;
__asm__(
"movl $20, %%eax;"
"movl $10, %%ebx;"
"subl %%ebx, %%eax;"
: "=a"(result));
cout << result;
return 0;
}
Output
10
Explanation
- 20 is loaded into register eax.
- 10 is loaded into register ebx.
- subl subtracts ebx from eax.
- The final value is stored in result.
Syntax
The asm declaration accepts assembly instructions as a string literal.
asm("assembly_instruction");
or
__asm__("assembly_instruction");
where: assembly_instruction is a valid assembly language instruction.
Common GCC Inline Assembly Conventions
When using inline assembly with GCC, it is important to understand a few syntax conventions.
Register Naming
Register names are prefixed with %.
%eax
%ebx
%ecx
%edx
Operand Ordering
GCC follows the AT&T syntax where the source operand appears before the destination operand.
movl %edx, %eaxThis copies the value of %edx into %eax.
Immediate Values
Constant values are prefixed with $.
addl $5, %eaxThis adds the value 5 to %eax.
Performing Arithmetic Operations Using asm
Inline assembly can be used to perform arithmetic operations directly through CPU instructions.
#include <iostream>
using namespace std;
int main()
{
int a = 100;
int b = 20;
int add, sub, mul;
asm("addl %%ebx, %%eax"
: "=a"(add)
: "a"(a), "b"(b));
asm("subl %%ebx, %%eax"
: "=a"(sub)
: "a"(a), "b"(b));
asm("imull %%ebx, %%eax"
: "=a"(mul)
: "a"(a), "b"(b));
cout << a << " + " << b << " = " << add << endl;
cout << a << " - " << b << " = " << sub << endl;
cout << a << " * " << b << " = " << mul << endl;
return 0;
}
Output
100 + 20 = 120 100 - 20 = 80 100 * 20 = 2000
Explanation
- addl performs addition.
- subl performs subtraction.
- imull performs multiplication.
- The results are transferred from registers back to C++ variables.
Limitations of asm Declaration
Although powerful, inline assembly should be used carefully.
- Reduces code portability across platforms and compilers.
- Makes programs harder to understand and maintain.
- Can limit compiler optimizations.
- Syntax differs between compilers such as GCC, Clang, and MSVC.