asm() 函数遵循以下顺序:
asm ( "assembly code"
: output operands /* optional */
: input operands /* optional */
: list of clobbered registers /* optional */
);
并通过您的 c 代码将 11 放到 x 中:
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 代码
asm ("movl %1, %0;"
:"=r"(x) /* related to %0*/
:"r"(11) /* related to %1*/
:);
您可以通过避免输入操作数并使用 asm 中的局部常量值而不是 c 中的值来简化更多:
asm ("movl $11, %0;" /* $11 is the value 11 to assign to %0 (related to x)*/
:"=r"(x) /* %0 is related x */
:
:);
另一个例子:compare 2 numbers with assembly