简体   繁体   中英

error: invalid 'asm': operand number missing after %-letter when using inline assembly with GCC

I'm tring to convert a simple assembly code of MS to use with gcc, the MS assembly I try to convert is right below. I have two int variables, number and _return :

mov eax, number
neg eax
return, eax

and, I have tried this:

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

But, the compiler gives me this error:

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

Where is the error, and, how I can fix this error? Thanks

You can't do it like that because you're overwriting registers without telling the compiler about it. Also, the % is a special character, similar to printf.

It's also better to put all the instructions in one asm or else the compiler might do something unexpected in between.

Try this instead:

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

There's probably a better way, though:

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

I don't know why you can't just do (in C):

_return = -number;

Try something like:

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

The issues are:

  • order of operands is instr src,dst
  • %% instead of %
  • no isolated lines of assembler -- the input/output/clobber list is associated to all of the assembler block
  • '+r' to have a parameter that works as both input & output
  • I doubt even MS allows using keyword "return" that way

And to make it even more efficient:

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

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