Skip to content

Instantly share code, notes, and snippets.

@tell
Created August 26, 2011 23:47
Show Gist options
  • Save tell/1174716 to your computer and use it in GitHub Desktop.
Save tell/1174716 to your computer and use it in GitHub Desktop.
Practice Inline ASM on GCC
#include <assert.h>
#include <stdio.h>
void in_emu_add(int *z, const int x, const int y)
{
*z = x + y;
}
void in_asm_add(int *z, const int x, const int y)
{
__asm__ volatile
(
"movl %0, %%eax\n\t"
"movl %1, %%edx\n\t"
"addl %2, %%edx\n\t"
"movl %%edx, (%%eax)\n\t"
:
: "g"(z), "g"(x), "g"(y)
: "eax", "edx"
);
}
void test()
{
puts(__func__);
int a = 1, b = 2, c, d;
in_emu_add(&c, a, b);
in_asm_add(&d, a, b);
printf("c=%d\n", c);
printf("d=%d\n", d);
assert(c == d);
}
int main()
{
int a = 1, b = 2, c, d;
in_emu_add(&c, a, b);
in_asm_add(&d, a, b);
printf("c=%d\n", c);
printf("d=%d\n", d);
assert(c == d);
test();
return 0;
}
# Build log
$ gcc-mp-4.6 -m32 -std=c99 -O3 -fomit-frame-pointer -Wall -Wextra -S -o add_asm.s add_asm.c
$ gcc-mp-4.6 -m32 -std=c99 -O3 -fomit-frame-pointer -Wall -Wextra -S -o add_asm_main.s add_asm_main.c
$ gcc-mp-4.6 -m32 -std=c99 -O3 -fomit-frame-pointer -Wall -Wextra -c -o add_asm_main.o add_asm_main.s
$ gcc-mp-4.6 -m32 -std=c99 -O3 -fomit-frame-pointer -Wall -Wextra -c -o add_asm.o add_asm.s
$ gcc-mp-4.6 -m32 add_asm_main.o add_asm.o -o add_asm_main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment