Skip to content

Instantly share code, notes, and snippets.

@Nkawu
Last active June 11, 2019 22:42
Show Gist options
  • Save Nkawu/4cb9da007d814ac7556a608585f91ff0 to your computer and use it in GitHub Desktop.
Save Nkawu/4cb9da007d814ac7556a608585f91ff0 to your computer and use it in GitHub Desktop.
Embedding assembly language into C into perl. Not sure if it serves any purpose other than being geeky.
#!/usr/bin/env perl
# cpanm Inline::C
use Inline 'C';
my $a = 10;
my $b = 15;
print "$a + $b = ", add_c_asm($a, $b), "\n";
printf "GCD of %d & %d = %d\n", $a, $b, gcd($a, $b);
__END__
__C__
int add_c_asm(int foo, int bar) {
__asm__ __volatile__("addl %%ebx,%%eax"
:"=a"(foo)
:"a"(foo), "b"(bar)
);
return foo;
}
int gcd( int a, int b ) {
int result;
/* Compute Greatest Common Divisor using Euclid's Algorithm */
__asm__ __volatile__ ("movl %1, %%eax;"
"movl %2, %%ebx;"
"CONTD: cmpl $0, %%ebx;"
"je DONE;"
"xorl %%edx, %%edx;"
"idivl %%ebx;"
"movl %%ebx, %%eax;"
"movl %%edx, %%ebx;"
"jmp CONTD;"
"DONE: movl %%eax, %0;" : "=g" (result) : "g" (a), "g" (b)
);
return result ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment