我有以下代码.我想完成汇编代码,如下所示:
int main(void)
{
int x = 10;
int i=0;
label1:
asm (.....) // code to add here: if i>=x then jump to label2
printf("%d\n",i);
i++;
asm (.....) // code to add here: jump to label 1
label2:
printf("out\n");
}
Run Code Online (Sandbox Code Playgroud)
我的机器是x86,操作系统是Ubuntu 12
首先,给自己一个x86操作码列表,应该很容易在网上找到.
该asm()函数遵循以下顺序:
asm ( "assembly code"
: output operands /* optional */
: input operands /* optional */
: list of clobbered registers /* optional */
);
Run Code Online (Sandbox Code Playgroud)
其次,你遇到的一个主要问题是你不能"跳"到C标签,你需要让你的标签成为一个"组装"标签,以便能够跳转到它.例如:
int main()
{
asm("jmp .end"); // make a call to jmp there
printf("Hello ");
asm(".end:"); //make a "jumpable" label
printf("World\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我们跳过"你好"时,这个程序的输出就是"世界".这是相同的例子,但有一个比较性的跳跃:
int main()
{
int x = 5, i = 0;
asm(".start:");
asm("cmp %0, %1;" // compare input 1 to 2
"jge .end;" // if i >= x, jump to .end
: // no output from this code
: "r" (x), "r" (i)); // input's are var x and i
printf("Hello ");
i++;
asm("jmp .start;");
asm(".end:");
printf("World\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)