How to access C variable for inline assembly manipulation?

亡梦爱人 提交于 2019-12-01 08:53:19
Aniket Inge

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)
);

after this, x contains 0.

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.

See https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html and https://stackoverflow.com/tags/inline-assembly/info for more docs and guides.


Not all compilers support GNU syntax. For example, for MSVC you do this:

__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.

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

asm("mov $0, %1":"=r" (x):"r" (x):"cc");
-- this may get you on the right track. Specify register use as much as possible for performance and efficiency. However, as Aniket points out, highly architecture dependent and requires gcc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!