通过内联汇编操作c变量 [英] manipulating c variable via inline assembly
问题描述
可能重复:
如何访问c变量以进行内联汇编操作
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,该怎么做?
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\n", 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屋!