You copied the Doc URL to your clipboard.

5.2. C/C++ inline assembly

In this section, we briefly cover how to include assembly code within C or C++ language modules.

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 %w[result], %w[input_i], %w[input_j]"    //Use `%w[name]` to operate on W
                                                     // registers (as in this case).
                                                     // You can use `%x[name]` for X
                                                     // registers too, but this is the
                                                     // default.
       : [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 [: clobber_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 this 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 this example, there are two input operands: [input_i] "r" (i) and [input_j] "r" (j).

clobber_list is an optional list of clobbered registers, or other values. In our example, this is omitted.

When calling functions between C/C++ and assembly code, you must follow the AAPCS64 rules.

For further information, see:

Was this page helpful? Yes No