【发布时间】:2016-10-23 16:44:44
【问题描述】:
考虑一下这段代码,来自我的earlier question。
int main(){
asm("movq $100000000, %rcx;"
"startofloop: ; "
"sub $0x1, %rcx; "
"jne startofloop; ");
}
我想将循环的迭代次数设为 C 变量,所以我在阅读 this document 后尝试了以下操作。
int main(){
int count = 100000000;
asm("movq %0, %rcx;"
"startofloop: ; "
"sub $0x1, %rcx; "
"jne startofloop; ":: "r"(count));
}
不幸的是,这无法编译,并因以下错误而中断。
asm_fail.c: In function ‘main’:
asm_fail.c:3:5: error: invalid 'asm': operand number missing after %-letter
asm("movq %0, %rcx;"
^
asm_fail.c:3:5: error: invalid 'asm': operand number missing after %-letter
将C变量的值传递给程序集的正确方法是什么?
【问题讨论】:
-
如果使用扩展的汇编器模板(带有输入、输出、clobbers 等的模板),那么您需要在寄存器名称前附加一个
%。也许试试%%rcx。由于您覆盖了 RCX 并且它不会显示为输出操作数,因此它需要列在 clobber 列表中。 -
@MichaelPetch,说得好。不幸的是,当我执行
%%rcx时,我得到了operand type mismatch for 'movq'。 -
是的,这可能是因为
count是一个 32 位整数,而汇编器模板选择了一个 32 位寄存器(如eax)进行替换。您可以通过在%之后放置q来覆盖%0以使用64 位寄存器,例如movq %q0, %%rcx; -
@MichaelPetch,这似乎可以解决问题。谢谢!
-
另请参阅the bottom of this answer 以了解有关使用 GNU C 内联 asm 制作不糟糕的代码的信息(例如,在模板中使用
movq而不是使用操作数约束来要求编译器进行设置为你)。在尽可能少地约束优化器的同时使其正确确实很难,而且它仍然无法通过内联汇编进行持续传播之类的事情。因此,通常最好调整 C 以将编译器保存为良好的 asm,而不是使用内联 asm。
标签: c gcc x86-64 inline-assembly att