2

假设这段代码:

int add(int a, int b){
    int c = a+b;
    return c;
}

int main(){
  printf("%d\n", add(3,4));
}

以下通常是在汇编中如何实现的:

- push 4 to stack
- push 3 to stack
- push return address which is the address of the next instruction, `print()` to stack
- call add
- do addition and push c on the stack
- pop c from stack ??
- return to main

那么返回值会发生什么,它不能在add框架上,因为它会在最后被清除。它会被放入堆栈main吗?

让我们假设这些值被推送到大头钉而不是寄存器。

4

1 回答 1

2

这取决于架构和调用约定。在 x86-32 中,几乎每个调用约定都有 64 位结果中的返回值eaxedx:eax用于 64 位结果的返回值。所以你的add函数可能有说明:

mov eax, dword ptr [esp+4] ; put 1st arg in eax
add eax, dword ptr [esp+8] ; add eax with 2nd arg
ret                        ; return

不需要额外的工作,因为返回值已经应该在eax.

也就是说,除非您询问特定的架构,否则您不会为此找到“一般情况”的答案,即使那样,它也可能有多种不同的调用约定。

于 2020-03-03T14:40:29.457 回答