Search code examples
gccassemblyinline-assembly

How to write multiline inline assembly code in GCC C++?


This does not look too friendly:

__asm("command 1"
      "command 2"
      "command 3");

Do I really have to put a doublequote around every line?

Also... since multiline string literals do not work in GCC, I could not cheat with that either.


Solution

  • I always find some examples on Internet that the guy manually insert a tab and new-line instead of \t and \n, however it doesn't work for me. Not very sure if your example even compile.. but this is how I do:

    asm volatile(           // note the backslash line-continuation
       "xor %eax,%eax          \n\t\
        mov $0x7c802446, %ebx  \n\t\
        mov $1000, %ax         \n\t\
        push %eax              \n\t\
        call *%ebx             \n\t\
        add $4, %esp           \n\t\
        "
        : "=a"(retval)        // output in EAX: function return value
        :
        : "ecx", "edx", "ebx"   // tell compiler about clobbers
      // Also x87 and XMM regs should be listed.
     );
    

    Or put double quotes around each line, instead of using \ line-continuation. C string literals separately only by whitespace (including a newline) are concatenated into one long string literal. (Which is why you need the \n inside it, so it's separate lines when it's seen by the assembler).

    This is less ugly and makes it possible to put C comments on each line.

    asm volatile(
        "xor %eax,%eax          \n\t"
        "mov $0x7c802446, %ebx  \n\t"
        "mov $1000, %ax         \n\t"
        "push %eax              \n\t"  // function arg
        "call *%ebx             \n\t"
        "add $4, %esp           \n\t"  // rebalance the stack: necessary for asm statements
      : "=a"(retval)
      :
      : "ecx", "edx", "ebx"    // clobbers.  Function calls themselves kill EAX,ECX,EDX
      // function calls also clobber all x87 and all XMM registers, omitted here
    );