Inline assembly allows embedding assembly instructions directly within C code, combining the low-level control of assembly with the high-level constructs of C.
Inline assembly is written using the asm
or __asm__
keyword in GCC:
asm("assembly code");
This example demonstrates adding two numbers using inline assembly.
#includeint main() { int a = 5, b = 3, result; asm("addl %%ebx, %%eax" : "=a"(result) /* Output */ : "a"(a), "b"(b) /* Inputs */ ); printf("Result: %d\n", result); return 0; }
\"=a\"(result)
: Output constraint. Stores the result in the eax
register.\"a\"(a)
: Input constraint. Places a
in the eax
register.\"b\"(b)
: Input constraint. Places b
in the ebx
register.Clobber tells the compiler which registers or memory the assembly code modifies:
asm("movl $0, %%eax" : : : "%eax" /* Clobber list */ );
Inline assembly can invoke system calls directly:
#include#include int main() { asm("mov $1, %rax\n" /* System call: write */ "mov $1, %rdi\n" /* File descriptor: stdout */ "mov $msg, %rsi\n" /* Message to print */ "mov $13, %rdx\n" /* Length of the message */ "syscall" ); return 0; } char msg[] = "Hello, world!\n";