【问题标题】:Following is some assembly code by VS2012, how can I write it on gcc?以下是VS2012的一些汇编代码,我如何在gcc上编写它?
【发布时间】:2013-11-14 10:36:33
【问题描述】:
#include <stdio.h>

int main ()
{
    int a = 0 ;
    /*How can I write it on gcc*/
    __asm {
         mov a, 2 ;
         add a, 4 ;
    }
    printf ("%d\n",a );
    return 0 ;
}

这是VS2012的一些汇编代码,在gcc上怎么写?

【问题讨论】:

  • 通过向谷歌询问数百万样本中的任何一个并复制样式。我在 google 中输入了“gcc inline asm”,得到了 19,400,000 个结果。也许你需要再努力一点?

标签: c assembly


【解决方案1】:

在 gcc 中可以这样写:

#include <stdio.h>

int main ()
{
  int a = 0 ;
  /*How can I write it on gcc*/
  __asm__ __volatile__ (
    "movl $2, %0\n\t"
    "addl $4, %0\n\t"
    :"=r"(a) /* =r(egister), =m(emory) both fine here */
  );
  printf ("%d\n",a );
  return 0 ;
}

【讨论】:

  • 谢谢你..这是我需要的
【解决方案2】:

例如创建另一个文件fun.s 并执行以下操作

.global my_fun #to show where program should start
     my_fun:
     push %ebp  #save stack ptr
     #function body
     pop %ebp   #recover stack ptr
 ret

然后只需在您的主函数中调用它

int main(){
my_fun();
}

像这样编译:g++ -o prog fun.s main.cpp

【讨论】:

    【解决方案3】:
    #include <stdio.h>
    
    int main ()
    {
        int a = 0 ;
        /*How can I write it on gcc*/
        asm volatile 
        (
             "mov $2, %0\n"
             "add $4, %0\n"
             : "=r"(a) /* output operand */
             : /* input operand */
             : /* clobbered operands */
        );
        printf ("%d\n",a );
        return 0 ;
    }
    

    请阅读GCC's extended asm syntax了解更多信息。

    【讨论】:

    • 呃..你的代码有问题..你能给我一些正确的代码吗?
    • 其实"=r"(a)是一个输出操作数
    • 感谢您指出这一点,我已经确定了答案。给您带来的不便,我们深表歉意。
    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 2012-02-12
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多