The __asm
keyword can incorporate inline GCC syntax assembly code into a function.
For example:
#include <stdio.h>
int add(int i, int j)
{
int res = 0;
__asm (
"ADD %[result], %[input_i], %[input_j]"
: [result] "=r" (res)
: [input_i] "r" (i), [input_j] "r" (j)
);
return res;
}
int main(void)
{
int a = 1;
int b = 2;
int c = 0;
c = add(a,b);
printf("Result of %d + %d = %d\n", a, b, c);
}
The general form of an __asm
inline assembly statement is:
__asm(code
[: output_operand_list
[: input_operand_list
[: clobbered_register_list
]]]);
code
is the assembly code. In our example, this is "ADD %[result], %[input_i], %[input_j]"
.
output_operand_list
is an optional list of output operands,
separated by commas. Each operand consists of a symbolic name in square brackets, a
constraint string, and a C expression in parentheses. In our example, there is a
single output operand: [result] "=r" (res)
.
input_operand_list
is an optional list of input operands, separated by commas. Input operands use the same syntax as output operands. In our example there are two input operands: [input_i] "r" (i), [input_j] "r" (j)
.
clobbered_register_list
is an optional list of clobbered registers. In our example, this is omitted.