2013-03-04 126 views
8

在gcc中,可以使用以下语法声明局部变量应放入寄存器中。如何使用gcc asm关键字在寄存器中传递函数参数

register int arg asm("eax"); 

在一些旧的代码我这句法来声明该参数的函数应该在寄存器传递在互联网上找到:

void foo(register int arg asm("eax")) 

但当我尝试这个例子:

/* 
    Program to demonstrate usage of asm keyword to allocate register for a variable. 
*/ 
#include <stdio.h> 

/* Function with argument passed in register */ 
void foo(register int arg asm("eax")) 
{ 
    register int loc asm("ebx"); 
    loc = arg; 
    printf("foo() local var: %d\n", loc); 
} 

int main(void) 
{ 
    foo(42); 
    return 0; 
} 

而且用gcc编译我得到一个错误:

gcc main.c -o test-asm.exe 
main.c:7:27: error: expected ';', ',' or ')' before 'asm' 

现在我的问题是:
是ASM的语法正确以上,在海湾合作委员会就是一个函数的形参?
这是否曾经被gcc支持?
如果这不是正确的语法,那么如何实现呢?

感谢,
// JK

回答

2

我所知道的是使用快速调用属性的唯一方法:

(GCC手册第6.30)http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html#Function-Attributes

fastcall

On the Intel 386, the fastcall attribute causes the compiler to pass the first argument (if of integral type) in the register ECX and the second argument (if of integral type) in the register EDX. Subsequent and other typed arguments are passed on the stack. The called function will pop the arguments off the stack. If the number of arguments is variable all arguments are pushed on the stack.

在使用它的以下示例代码:

__attribute__((fastcall,noinline)) int add (int a, int b) 
{ 
    return a + b; 
} 

int main() { 
    return add (1, 2); 
} 

将导致:

.file "main.c" 
    .text 
.globl add 
    .type add, @function 
add: 
    pushl %ebp 
    movl %esp, %ebp 
    leal (%edx,%ecx), %eax 
    popl %ebp 
    ret 
    .size add, .-add 
.globl main 
    .type main, @function 
main: 
    pushl %ebp 
    movl %esp, %ebp 
    movl $2, %edx 
    movl $1, %ecx 
    call add 
    popl %ebp 
    ret 
    .size main, .-main 

不要忘记提及在其他翻译单元的任何声明FASTCALL属性,否则很奇怪的事情可能会发生。

+0

感谢您的建议。但是我认为可能有或者已经有了gcc支持的更一般的语法。 – 2013-03-04 20:47:43

+0

哇,超过一半的生成函数是多么丑陋无用的序幕/尾声废话......那是用'-O0'还是...? – 2013-03-04 22:52:07

+0

Nope - 与-O0相比,它变得更加有趣,因为参数通过ecx和edx传递,无论出于何种原因将首先存储在堆栈中。这是(不笑话)将做什么用的gcc -O0:'补充: \t pushl \t%EBP \t MOVL \t%ESP,EBP% \t subl \t $ 8%ESP \t MOVL \t%ECX,-4( %EBP) \t \t MOVL%EDX,-8(%EBP) \t \t MOVL -8(%EBP),%eax中 \t \t MOVL -4(%EBP),%EDX \t \t莱亚尔(%EDX, %eax),%eax \t请假 \t ret' – mikyra 2013-03-04 23:28:05

相关问题