Calling a C function in assembly [duplicate]

徘徊边缘 提交于 2019-12-11 12:39:28

问题


Despite I searched everywhere I couldn't find any solution to my problem.The problem is that I I defined a function "hello_world() " in a C file "hello.c" and I want to call this function in an assembly file . "hello_assembly.asm" .Can anyone help me ? Thank you.


回答1:


You could check the below example which might give some idea.

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

mymul is a function which is being written in assembly language in file called mymul.S

Below is the code for 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

We use the command "cc" to compile our above programs

$ cc mymul.S mul.c -o mulprogram

In the mul.c when we call mymul, we are passing address of a and b , and these address are getting pushed to the stack. When the execution of program enters the mymul function, the stack looks like this: addressofb,addressofa, returnaddress, oldebp


we get the value stored in the address of a and address of b using xchg(we could use movl here) , do the multiplication and save the result in b.


I hope the above program helps you.



来源:https://stackoverflow.com/questions/21031072/calling-a-c-function-in-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!