Course contentsShow
← C
Lesson 963 of 1,21913. Advanced CFree lesson

Platform-specific assembly (x86 vs ARM)

Platform-specific assembly (x86 vs ARM)

What you'll learn: Understand why inline assembly is not portable and how to bridge the gap between different CPU architectures.

The Language of the Processor

C is often called "portable assembly," but when you use the asm keyword, you lose that portability. Every CPU family speaks its own native language. If you write assembly for an Intel-based laptop (x86_64), it will be gibberish to a Raspberry Pi or an iPhone (ARM).

Think of it like local slang. If you go to a restaurant in London and ask for "chips," you get fries. If you go to New York and ask for "chips," you get a bag of crisps. In C, a command like mov might exist on both platforms, but the order of the inputs and how the CPU handles them is completely different.

Architecture Clashes

The two main titans you will encounter are x86 (Complex Instruction Set) and ARM (Reduced Instruction Set).

  1. x86 (Intel/AMD): Uses a "Register-Memory" architecture. Many instructions can perform math directly on data stored in RAM. It’s famous for having variable-length instructions.
  2. ARM (Apple Silicon/Mobile): Uses a "Load-Store" architecture. You cannot do math on a memory address; you must load the value into a register first, do the work, and then store it back.

How to Handle Both

To write professional, low-level C, you use preprocessor macros. This allows the compiler to "pick" the correct assembly block based on the machine it is currently building for.

#include <stdio.h>

int main() {
    int result;

    #if defined(__x86_64__)
        // x86_64 syntax: move the number 42 into the 'result' variable
        asm ("movl $42, %0" : "=r" (result));
    #elif defined(__aarch64__)
        // ARM64 syntax: move the number 42 into the 'result' variable
        asm ("mov %0, #42" : "=r" (result));
    #else
        // Fallback for other platforms
        result = 42;
    #endif

    printf("The answer is: %d\n", result);
    return 0;
}

In the code above, the compiler checks the hardware identity. If it sees __x86_64__, it ignores the ARM code entirely. This prevents your program from crashing during the build process on different machines.

Key takeaway

Inline assembly is platform-locked; always use preprocessor guards (#if defined) to provide specific implementations for different CPU architectures.