6

可能重复:
如何访问 c 变量以进行内联汇编操作

鉴于此代码:

#include <stdio.h>

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


  }

我想访问和操作内联汇编中的变量 x 。理想情况下,我想使用内联汇编来改变它的值。GNU 汇编器,并使用 AT&T 语法。假设我想在 printf 语句之后将 x 的值更改为 11,我该怎么做呢?

4

1 回答 1

10

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 */
    :
    :);

另一个例子:将 2 个数字与汇编进行比较

于 2013-01-31T15:33:01.863 回答