Inline Assembly in C
Inline assembly allows embedding assembly instructions directly within C code, combining the low-level control of assembly with the high-level constructs of C.
Syntax
Inline assembly is written using the asm or __asm__ keyword in GCC:
asm("assembly code");
Example: Adding Two Numbers
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; }
Explanation
\"=a\"(result): Output constraint. Stores the result in theeaxregister.\"a\"(a): Input constraint. Placesain theeaxregister.\"b\"(b): Input constraint. Placesbin theebxregister.
Clobbers
Clobber tells the compiler which registers or memory the assembly code modifies:
asm("movl $0, %%eax"
:
:
: "%eax" /* Clobber list */
);
Example: Inline Assembly for System Calls
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";
Key Notes
- Always declare clobbers to avoid unpredictable behavior.
- Inline assembly is highly dependent on the compiler and processor architecture.
- For complex assembly, consider writing a separate assembly file and linking it with C code.