通过内联汇编操作 c 变量 [英] manipulating c variable via inline assembly
问题描述
可能的重复:
如何访问 c 变量进行内联汇编操作
鉴于此代码:
#include <stdio.h>
int main(int argc, char **argv)
{
int x = 1;
printf("Hello x = %d
", x);
}
我想在内联汇编中访问和操作变量 x.理想情况下,我想使用内联汇编更改其值.GNU 汇编器,并使用 AT&T 语法.假设我想在 printf 语句之后将 x 的值更改为 11,我该怎么做?
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?
推荐答案
asm()
函数遵循以下顺序:
asm ( "assembly code"
: output operands /* optional */
: input operands /* optional */
: list of clobbered registers /* optional */
);
并通过您的 c 代码将 11 与 x 结合起来:
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
", x);
}
您可以通过避免损坏的寄存器来简化上面的 asm 代码
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*/
:);
您可以通过避免输入操作数并使用来自 asm 的局部常量值而不是来自 c 的局部常量值来进一步简化:
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 */
:
:);
另一个例子:比较2个数字和汇编
这篇关于通过内联汇编操作 c 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!