How do I access the C variable to manipulate the inline assembly?

Given this code:

#include <stdio.h>

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

      

I would like to access and manipulate the x variable in an inline assembly. Ideally I want to change its value using inline assembly. GNU assembler, and using AT&T syntax.

+3


source to share


2 answers


In GNU C, built-in 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 that x contains 0.

Note that you should generally avoid the mov

asm statement as the first or last statement. Don't copy from %[some]

to a hard-coded register such as %%eax

, just use %[some]

as a register, allowing the compiler to allocate registers.

See https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html and fooobar.com/questions/tagged / ... for more docs and guides.




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

__asm mov x, 0

and x

will be meaningful 0

after this statement.

Please indicate the compiler you want to use.

Also note that doing this will restrict your program to compile with only a specific compiler-assembler combination, and will only target a specific architecture.

In most cases, you will get just as good or better results from using pure C and built-in functions rather than built-in asm.

+4


source


asm("mov $0, %1":"=r" (x):"r" (x):"cc");


- it can lead you on the right path. State the maximum possible use of the registry for performance and efficiency. However, as Aniket points out, the architecture is highly dependent and requires gcc.



0


source







All Articles