Linux C语言内联汇编-函数调用

int func(int a, int b, int c, int d, int e, int x, int y, int z){
    return 1;
}

int main() {

    res = func(1, 2, 3, 4, 5, 6, 7, 8);
    cout << res;
    return 0;
}

g++ -S查看汇编

subq	$16, %rsp
pushq	$8
pushq	$7
movl	$6, %r9d
movl	$5, %r8d
movl	$4, %ecx
movl	$3, %edx
movl	$2, %esi
movl	$1, %edi
call	_Z4funciiiiiiii
addq	$16, %rsp
movl	%eax, -4(%rbp)

从右向左依次传参;
x86-64 Linux貌似就这一种调用约定,参考:x64 linux c 调用约定

其他参考:C语言函数调用约定

了解调用规则后,再看汇编应该怎么写;

int func(int x, int y){
    return x * y;
}

int main() {

    int res, agrx = 2, agry = 3;

    __asm__("movl %2, %%esi;"   //传参
            "movl %1, %%edi;"
            "call %3;"          //调用func
            "movl %%eax, %0;"   //返回值在%eax,res = %eax;
            :"=r"(res)
            :"r"(agry), "r"(agrx), "r"(func)
            );

    cout << res;

    return 0;
}

查看对应的.s文件:

	subq	$16, %rsp
	movl	$2, -4(%rbp)
	movl	$3, -8(%rbp)
	movl	-8(%rbp), %eax
	movl	-4(%rbp), %edx
	leaq	_Z4funcii(%rip), %rcx
#APP
# 36 "main.cpp" 1
	movl %edx, %esi;movl %eax, %edi;call %rcx;movl %eax, %eax;
# 0 "" 2
#NO_APP
	movl	%eax, -12(%rbp)

猜你喜欢

转载自blog.csdn.net/M_N_N/article/details/80785609