w1coding.comAll tutorials

Assembly Inline

Assembly lessons
  1. Environment Setup
  2. Introduction
  3. Syntax
  4. Datamovement
  5. Operators
  6. Control
  7. Loops
  8. Interupts
  9. Functions
  10. Memory
  11. System
  12. Debugging
  13. Macros
  14. Execution
  15. Floating
  16. Interupts
  17. Optimization
  18. Linking
  19. Inline
  20. Registers
  21. Bootloader
  22. Macros
  23. Stack
  24. Call
  25. Technique
  26. Responsive

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

  • \"=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.

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.