How to access C variable for inline assembly manipulation?

后端 未结 2 1346
暖寄归人
暖寄归人 2020-12-02 01:11

Given this code:

#include 

int main(int argc, char **argv)
{
    int x = 1;
    printf(\"Hello x = %d\\n\", x);
}

I\'d like

相关标签:
2条回答
  • 2020-12-02 01:31

    asm("mov $0, %1":"=r" (x):"r" (x):"cc");
    -- this may get you on the right track. Specify register use as much as possible for performance and efficiency. However, as Aniket points out, highly architecture dependent and requires gcc.

    0 讨论(0)
  • 2020-12-02 01:44

    In GNU C inline asm, with x86 AT&T syntax:
    (But https://gcc.gnu.org/wiki/DontUseInlineAsm if you can avoid it).

    // this example doesn't really need volatile: the result is the same every time
    asm volatile("movl $0, %[some]"
        : [some] "=r" (x)
    );
    

    after this, x contains 0.

    Note that you should generally avoid mov as the first or last instruction of an asm statement. Don't copy from %[some] to a hard-coded register like %%eax, just use %[some] as a register, letting the compiler do register allocation.

    See https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html and https://stackoverflow.com/tags/inline-assembly/info for more docs and guides.


    Not all compilers support GNU syntax. For example, for MSVC you do this:

    __asm mov x, 0 and x will have the value of 0 after this statement.

    Please specify the compiler you would want to use.

    Also note, doing this will restrict your program to compile with only a specific compiler-assembler combination, and will be targeted only towards a particular architecture.

    In most cases, you'll get as good or better results from using pure C and intrinsics, not inline asm.

    0 讨论(0)
提交回复
热议问题