inline

Inline Assembly in C

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.

#include 

int 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

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