通过内联汇编操作c变量

时间:2013-01-31 15:07:32

标签: c assembly inline-assembly

  

可能重复:
  How to access c variable for inline assembly manipulation

鉴于此代码:

#include <stdio.h>

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


  }

我想在内联汇编中访问和操作变量x。理想情况下,我想使用内联汇编更改其值。 GNU汇编程序,并使用AT&amp; T语法。假设我想将x的值更改为11,就在printf语句之后,我将如何进行此操作?

1 个答案:

答案 0 :(得分:5)

asm()函数遵循以下顺序:

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

并通过你的c代码将11放到x组装:

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);
}

您可以通过避免使用被破坏的寄存器来简化上述asm代码

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

您可以通过避免输入操作数和使用来自asm的本地常量值而不是c来简化更多:

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

另一个例子:compare 2 numbers with assembly