Search code examples
c++inline-assembly

Expected ')' before token inline assembly error


I would like to learn some inline assembly programming, but my first cod snippet does not work. I have a string and I would like to assign the value of the string to the rsi register.

Here is my code:

    string s = "Hello world";
    const char *ystr = s.c_str();
    asm("mov %1,%%rsi"
    :"S"(ystr)
    :"%rsi" //clobbered register
);

    return 0;

It gives me the error :Expected ')' before token. Any help is appreciated.


Solution

  • You left out a : to delimit the empty outputs section. So "S"(ystr) is an input operand in the outputs section, and "%rsi" is in the inputs section, not clobbers.

    But as an input it's missing the (var_name) part of the "constraint"(var_name) syntax. So that's a syntax error, as well as a semantic error. That's the immediate source of the error <source>:9:5: error: expected '(' before ')' token. https://godbolt.org/z/97aTdjE8K


    As Nate pointed out, you have several other errors, like trying to force the input to pick RSI with "S".

       char *output;   // could be a dummy var if you don't actually need it.
       asm("mov %1, %0"
         : "=r" (output)     /// compiler picks a reg for you to write to.
        :"S"(ystr)           // force RSI input
        :   // no clobbers
       );
    

    Note that this does not tell the compiler that you read or write the pointed-to memory, so it's only safe for something like this, which copies the address around but doesn't expect to read or write the pointed-to data.

    Also related: