如何访问C变量以进行内联汇编操作? [英] How to access C variable for inline assembly manipulation?

查看:56
本文介绍了如何访问C变量以进行内联汇编操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

#include <stdio.h>

int main(int argc, char **argv)
{
    int x = 1;
    printf("Hello x = %d\n", 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嵌入式asm中,使用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.

请注意,通常应避免将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, 0x的值将为0.

请指定您要使用的编译器.

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和内在函数而不是内联asm会得到相同或更好的结果.

In most cases, you'll get as good or better results from using pure C and intrinsics, not inline asm.

这篇关于如何访问C变量以进行内联汇编操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆