如何访问 C 变量以进行内联汇编操作? [英] 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
", x);
}
我想在内联汇编中访问和操作变量 x.理想情况下,我想使用内联汇编更改其值.GNU 汇编程序,并使用 AT&T 语法.
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.
推荐答案
在 GNU C 内联汇编中,使用 x86 AT&T 语法:
(但是 https://gcc.gnu.org/wiki/DontUseInlineAsm 如果可以避免的话).
In GNU C inline asm, with x86 AT&T syntax:
(But https://gcc.gnu.org/wiki/DontUseInlineAsm if you can avoid it).
// this example doesn't really need volatile: the result is the same every time
asm volatile("movl $0, %[some]"
: [some] "=r" (x)
);
在此之后,x 包含 0.
after this, x contains 0.
请注意,通常应避免将 mov
作为 asm 语句的第一条或最后一条指令.不要从 %[some]
复制到像 %%eax
这样的硬编码寄存器,只需使用 %[some]
作为寄存器,让编译器进行寄存器分配.
Note that you should generally avoid mov
as the first or last instruction of an asm statement. Don't copy from %[some]
to a hard-coded register like %%eax
, just use %[some]
as a register, letting the compiler do register allocation.
参见 https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html 和 https://stackoverflow.com/tags/inline-assembly/info 获取更多文档和指南.
See https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html and https://stackoverflow.com/tags/inline-assembly/info for more docs and guides.
并非所有编译器都支持 GNU 语法.例如,对于 MSVC,您可以这样做:
Not all compilers support GNU syntax. For example, for MSVC you do this:
__asm mov x, 0
和 x
在此语句后将具有 0
的值.
__asm mov x, 0
and x
will have the value of 0
after this statement.
请指定您要使用的编译器.
Please specify the compiler you would want to use.
另请注意,这样做会限制您的程序仅使用特定的编译器-汇编器组合进行编译,并且仅针对特定架构.
Also note, doing this will restrict your program to compile with only a specific compiler-assembler combination, and will be targeted only towards a particular architecture.
在大多数情况下,使用纯 C 和内在函数,而不是内联汇编,您将获得同样或更好的结果.
In most cases, you'll get as good or better results from using pure C and intrinsics, not inline asm.
这篇关于如何访问 C 变量以进行内联汇编操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!