In the recent few weeks, I have started learning how to incorporate assembly code to C code. Some examples of those can be found easily over internet, but only a few of them provide a fully working inline assembly code when I tried to execute the code in my compiler.
So this writing is sort of documentation of my study through this topic. The codes here are tested under Dev C compiler and produce result as expected.
Without any further ado, the following codes demonstrate the way of acquiring value produced by a C function.
#include <stdio.h>>
int foo() {
return 2;
}
int main() {
int ivar; //to retrieve value of foo function
asm(“call _foo” : “=r” (ivar)); //return value of foo is stored in ivar variable
//printf(“%d\n”, ivar); //uncomment this line to print ivar to stdout
//getchar(); //uncomment this line to freeze the text console; otherwise it will disappear immediately
return 0;
}
The above code can be expanded by modifying foo function. This time, foo function returns value which is defined inside main function.
#include <stdio.h>
int foo(int fooParam) {
return fooParam;
}
int main() {
int ivar; //to retrieve value of foo function
asm(“movl $10, %eax”); //to copy constant 10 into eax register
asm(“push %eax”); //to push the value to the top of memory stack
asm(“call _foo” : “=r” (ivar)); //return value of foo is stored in ivar variable
//printf(“%d\n”, ivar); //uncomment this line to print ivar to stdout
//getchar(); //uncomment this line to freeze the text console; otherwise it will disappear immediately
return 0;
}
This is the end of my first writing related to inline assembly. I will add more writing on this topic in my future spare time.