July 02, 2018

Example to use Inline-assembly in C language

The method using assembly code in C language is called Inline-assembly.


[Example 1]
#include<stdio.h>

int main() {

    int a = 0;
    int b = 0;
    int c = 0;

    printf("Hello world\n");

    __asm__ __volatile__(
        "mov $2, %%eax;"
        "mov %%eax, %0;"
        "mov $10, %%ebx;"
        "mov %%ebx, %1"
        : "=m" (a), "=m" (c)
    );


    __asm__ __volatile__(
        "mov $5, %%ebx;"
        "mov %%ebx, %0"
        : "=m" (b)
    );

    printf("Result(a) : %d\n", a);
    printf("Result(c) : %d\n", c);
    printf("Result(b) : %d\n", b);


    int src = 3;
    int dst = 5;
    __asm__ volatile (
        "mov %1, %%eax;"
        "add $1, %%eax;"
        "mov %%eax, %0;"
        : "=m" (dst)
        : "m" (src)
    );

    printf("Result(add) : %d\n", dst);

    system("pause");
    return 0;
}

[Example 1 : result]
Hello world
Result(a) : 2
Result(c) : 10
Result(b) : 5
Result(add) : 4

❑ : "=m" (dst) → The result is output to the dst using memory.
❑ : "=r" (dst) → The result is output to the dst using a register. 
❑ : "m" (src) → The src value is input using memory.
❑ : "=m" (dst) : "m" (src)  %0 points to the dst and %1 points to the src.
❑ __volatile__ → The assembly code is executed where it is located and doesn't move for reasons such as optimization.