user1888502
user1888502

Reputation: 373

How to access C variable for inline assembly manipulation?

Given this code:

#include <stdio.h>

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

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

Upvotes: 7

Views: 7424

Answers (2)

Aniket Inge
Aniket Inge

Reputation: 25723

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.

Upvotes: 5

Rico
Rico

Reputation: 11

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.

Upvotes: 0

Related Questions