7

Possible Duplicate:
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. Suppose I want to change the value of x to 11, right after the printf statement, how would I go by doing this?

Community
  • 1
  • 1
user1888502
  • 343
  • 2
  • 7
  • 15
  • See https://stackoverflow.com/tags/inline-assembly/info, and other relevant Q&As: [Why can't local variable be used in GNU C basic inline asm statements?](https://stackoverflow.com/q/60227941) / [Code blocks Ver.16.01 crashing during run cycle of programme](https://stackoverflow.com/a/41117655) – Peter Cordes Jan 21 '21 at 20:33

1 Answers1

13

The asm() function follows this order:

asm ( "assembly code"
           : output operands                  /* optional */
           : input operands                   /* optional */
           : list of clobbered registers      /* optional */
);

and to put 11 to x with assembly via your c code:

int main()
{
    int x = 1;

    asm ("movl %1, %%eax;"
         "movl %%eax, %0;"
         :"=r"(x) /* x is output operand and it's related to %0 */
         :"r"(11)  /* 11 is input operand and it's related to %1 */
         :"%eax"); /* %eax is clobbered register */

   printf("Hello x = %d\n", x);
}

You can simplify the above asm code by avoiding the clobbered register

asm ("movl %1, %0;"
    :"=r"(x) /* related to %0*/
    :"r"(11) /* related to %1*/
    :);

You can simplify more by avoiding the input operand and by using local constant value from asm instead from c:

asm ("movl $11, %0;" /* $11 is the value 11 to assign to %0 (related to x)*/
    :"=r"(x) /* %0 is related x */
    :
    :);

Another example: compare 2 numbers with assembly

Community
  • 1
  • 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • See also https://stackoverflow.com/tags/inline-assembly/info for guides, and the official docs are better than when this answer was posted: https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html. (And the neighbouring pages in the manual about generic and machine-specific constraints.) See also https://gcc.gnu.org/wiki/DontUseInlineAsm - avoid it when you can get the compiler to make the asm you want from C intrinsics: much less chance of mistakes (like destroying a register or memory location without telling the compiler) that create undefined behaviour. – Peter Cordes Dec 18 '20 at 18:28