简体   繁体   中英

Following is some assembly code by VS2012, how can I write it on gcc?

#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 ;
}

This is some assembly code by VS2012, how can I write it on gcc?

#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 ;
}

Please read GCC's extended asm syntax for further information.

For example create another file fun.s and do following

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

Then simply invoke it in your main function

int main(){
my_fun();
}

Compile like this: g++ -o prog fun.s main.cpp

You can write it in gcc as:

#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 ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM