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