显然没有可移植的方式,因为允许编译器对函数做很多事情:从内联到尾调用优化。
但严格来说,没有什么可衡量的,因为编译器完全知道这个数字。好吧,除非您使用非常量大小的堆栈数组(在 C99 中允许,但在 C++ 中不允许)。
一种愚蠢的方法是查看汇编代码:
例如这个函数:
int f(int x, int y)
{
int z = x + y;
int h = z - 2;
return h;
}
在amd64上编译为:
f:
.LFB0:
.cfi_startproc
pushq %rbp ; save the pointer to the caller's frame
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp ; new frame starts from %rsp (current stack ptr)
; starting from this place look how %rbp is used
; the maximum offset is what you're looking for
.cfi_def_cfa_register 6
movl %edi, -20(%rbp)
movl %esi, -24(%rbp)
movl -20(%rbp), %edx
movl -24(%rbp), %eax
addl %edx, %eax
movl %eax, -8(%rbp)
movl -8(%rbp), %eax
subl $2, %eax
movl %eax, -4(%rbp)
movl -4(%rbp), %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
因此,在此示例中,函数 f 将 8 字节 %rbp(旧帧指针)推送到堆栈,然后它使用 %rbp-20、%rbp-24、%rbp-8 和 %rbp-4 处的内存。最大偏移量为 -24。
使用的总字节数是 24 字节加上 8 字节用于 %rbp 和 8 字节在这里不可见的返回指针,如果我没有忘记任何东西,总共 40 字节。
我不确定这是不是你问的。