今天午饭时跟同事争论C语言参数传递的问题,同事有ARM开发经验,坚信ARM上的参数传递是通过寄存器的,我在32位x86上面做过实验,也坚信栈传递的方法。
讨论并查了资料后,把学到了点东西记录下来。
32位x86上面,C语言参数传递是压栈出栈的过程,即使加上-O2或者-O3的优化选项,主要原因是32位x86寄存器稀缺的原因。但是如果在编译时加上-mregparm=num选项,参数传递就是用寄存器传递了。但遗憾的是num最大值不能超过3。
以下是man gcc中对-mregparm的解释
-mregparm=num
Control how many registers are used to pass integer arguments. By default, no registers are used to pass arguments, and at most 3
registers can be used. You can control this behavior for a specific function by using the function attribute regparm.
Warning: if you use this switch, and num is nonzero, then you must build all modules with the same value, including any libraries.
This includes the system libraries and startup modules.
64位x86上面,寄存器的个数比32位多了许多,默认就是用寄存器来参数传递的,谁让人家变得资源丰富了呢。
遗留的问题有:
由哪几个寄存器负责参数传递?
只能传递几个参数,或者几个字节?
64位x86上面能不能关闭寄存器参数传递的功能?