在程序集中调用C函数

尽管我到处搜索,但我找不到解决问题的方法。问题是我在C文件“hello.c”中定义了一个函数“hello_world()”,我想在汇编文件中调用此函数。 “hello_assembly.asm”。任何人都可以帮帮我吗? 谢谢。

你可以查看下面的例子,它可能会给你一些想法。

\#include  int main(void) { signed int a, b; a=5,b=25; mymul(&a,&b); printf("\nresult=%d",b); return 0; } 

mymul是一个用汇编语言编写的函数,名为mymul.S

以下是mymul.S的代码

 .globl mymul mymul: pushl %ebp # save the old base pointer register movl %esp, %ebp #copy the stack pointer to base pointer register movl 8(%ebp), %eax # get the address of a movl 12(%ebp), %ebx # get the address of b xchg (%eax), %ecx # we get the value of a and store it in ecx xchg (%ebx), %edx # we get the value of b and stored it in edx imul %ecx,%edx # do the multiplication xchg %ecx, (%eax) #save the value back in a xchg %edx, (%ebx) # save the value back in b movl %ebp, %esp # get the stack pointer back to ebp popl %ebp #restore old ebp ret #back to the main function 

我们使用命令“cc”来编译我们的上述程序

 $ cc mymul.S mul.c -o mulprogram 

在我们调用mymul的mul.c中,我们传递a和b的地址,这些地址被推送到堆栈。 当程序执行进入mymul函数时,堆栈如下所示:addressofb,addressofa,returnaddress,oldebp

我们使用xchg得到存储在a的地址和b的地址中的值(我们可以在这里使用movl),进行乘法并将结果保存在b中。

我希望上面的程序可以帮到你。

gcc调用约定

gcc文档应该更详细地说明这一点。

如果您找不到编译器和环境的文档,我建议您将C函数编译为汇编程序列表,并查看它是否希望在退出时传递参数以及它在堆栈中留下的内容。