c - 通过内联汇编操作 c 变量

标签 c assembly inline-assembly

<分区>

Possible Duplicate:
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&T 语法。假设我想在 printf 语句之后将 x 的值更改为 11,我将如何执行此操作?

最佳答案

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

关于c - 通过内联汇编操作 c 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14628885/

相关文章:

assembly - 无法弄清楚程序集 x86 中的 printf 函数以及使用操作数

c - 如何将数据与内联汇编进行比较?

c++ - 使用 gcc 编译内联汇编时出错, "shl"

assembly - 如何在 x86 ASM 中自动移动 64 位值?

c++ - 我怎样才能使用我的CPU的MM0到MM7寄存器?

选择最合适的整数大小/范围用于变量

c - CMBC 未报告看似无效的内存访问

对角检查二维数组?

c - 在哪些版本的 C 标准中,可变长度数组不是语言的一部分,是必需的还是可选的?

assembly - 引导加载程序可在模拟器中运行,但不能在真实硬件中运行