论证传递是如何工作的? [英] How does argument passing work?

查看:65
本文介绍了论证传递是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将参数传递给C中的函数.值存储在哪里以及如何以及如何检索它们?可变参数论证传递是如何工作的?也是因为它与之相关:返回值呢?

I want to know how passing arguments to functions in C works. Where are the values being stored and how and they retrieved? How does variadic argument passing work? Also since it's related: what about return values?

我对CPU寄存器和汇编器有基本的了解,但还不足以使我完全理解GCC向我吐出来的ASM.一些简单的带注释的示例将不胜感激.

I have a basic understanding of CPU registers and assembler, but not enough that I thoroughly understand the ASM that GCC spits back at me. Some simple annotated examples would be much appreciated.

推荐答案

考虑此代码:

int foo (int a, int b) {
  return a + b;
}

int main (void) {
  foo(3, 5);
  return 0;
}

使用gcc foo.c -S进行编译可提供程序集输出:

Compiling it with gcc foo.c -S gives the assembly output:

foo:
    pushl   %ebp
    movl    %esp, %ebp
    movl    12(%ebp), %eax
    movl    8(%ebp), %edx
    leal    (%edx,%eax), %eax
    popl    %ebp
    ret

main:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $8, %esp
    movl    $5, 4(%esp)
    movl    $3, (%esp)
    call    foo
    movl    $0, %eax
    leave
    ret

因此,基本上,调用方(在本例中为main)首先在堆栈上分配8个字节以容纳两个参数,然后将两个参数以相应的偏移量(40)放在堆栈上,然后发出call指令,该指令将控制权转移到foo例程. foo例程从堆栈上相应的偏移量读取其参数,将其还原,然后将其返回值放入eax寄存器中,以便调用者可以使用.

So basically the caller (in this case main) first allocates 8 bytes on the stack to accomodate the two arguments, then puts the two arguments on the stack at the corresponding offsets (4 and 0), and then the call instruction is issued which transfers the control to the foo routine. The foo routine reads its arguments from the corresponding offsets at the stack, restores it, and puts its return value in the eax register so it's available to the caller.

这篇关于论证传递是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆