2013-02-27 502 views
0

我正在转换MS的简单汇编代码与gcc一起使用,我尝试转换的MS汇编就在下面。我有两个int变量,number_return使用内联汇编与GCC

mov eax, number 
neg eax 
return, eax 

和,我已经试过这样:

asm("movl %eax, %0" :: "g" (number)); 
asm("neg %eax"); 
asm("movl %0, %%eax" : "=g" (return)); 

但是,编译器给了我这个错误:

main.c:17:9: error: invalid 'asm': operand number missing after %-letter

在哪里错误,以及,我如何解决这个错误? 谢谢

回答

3

你不能这样做,因为你覆盖寄存器而不告诉编译器。此外,%是一个特殊字符,与printf类似。

将所有指令放在一个asm中,否则编译器可能在之间做一些意想不到的事情也更好。

试试这个:

asm("movl %%eax, %1\n\t" 
    "neg %%eax\n\t" 
    "movl %0, %%eax" : "=g" (_return) : "g" (number) : "eax"); 

有可能是一个更好的办法,但:

asm("neg %0\n\t": "=a" (_return) : "a" (number)); 

我不知道为什么你不能只是做(在C):

_return = -number; 
+0

看到生成汇编,我看到:...“MOV \t DWORD PTR [ESP + 24],0。 ..“%eax,ebx”...“”neg%eax“”movl ebx,%eax“(该变量是错误的:() – Alexandre 2013-02-27 14:02:23

+0

我现在测试了这些。两者都有效。 – ams 2013-02-27 14:07:15

+0

我只是研究:) – Alexandre 2013-02-27 14:08:51

3

尝试类似:

#include <stdio.h> 
#include <stdlib.h> 
int main(int ac,char**av) 
{ 
    int n=ac>1?atoi(av[1]):42; 
    asm ("movl %0, %%eax \n\t" 
     "neg %%eax \n\t" 
     "movl %%eax, %0 \n\t" : "+r" (n)::"eax"); 
    printf("%d\n",n); 
}  

的问题是:

  • 操作数的顺序是instr src,dst
  • %%代替%
  • 汇编没有孤立线 - 输入/输出/撞列表被关联到所有汇编程序的方框
  • “+ R”为具有可以作为两个输入输出&
  • 我怀疑甚至MS允许使用关键字的参数“回归” 这样

,并使其更加有效:

asm("neg %0" : "+r" (n) ::); // works as well 
+0

好的,但我怎么能把(eax)放在_return变量上? – Alexandre 2013-02-27 14:03:38

+0

你是在正确的轨道上 - 我只是无法弄清楚问题中的所有重要规范:它是'asm(“mov%1,%0 \ n \ t neg%0 \ n \ t”: “= r”(_return_value):“r”(input):);'如果你稍后'返回_return_value',gcc很可能会将'eax'指定为寄存器'%0'。 – 2013-02-27 14:19:15