-1

我有以下代码。我想完成如下所示的汇编代码:

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

我的机器是 x86,操作系统是 Ubuntu 12

4

3 回答 3

5

首先,给自己一个 x86 操作码列表,应该很容易在网上找到。

asm()函数遵循以下顺序:

asm ( "assembly code"
           : output operands                  /* optional */
           : input operands                   /* optional */
           : list of clobbered registers      /* optional */
);

其次,您遇到的一个主要问题是您不能“跳转”到 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;
}

当我们跳过“Hello”时,该程序的输出只是“World”。这是相同的示例,但有一个比较跳跃:

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;
}
于 2013-01-25T14:30:01.693 回答
2

如果您不是真的必须在这里使用汇编,您可以更轻松地使用 C,并且至少与汇编版本一样高效:

int x = 10;
int i = 0;
while(i < x) {
  printf("%d\n",i);
  i++;
}
printf("out\n");

(a for-loop 也适用)

于 2013-01-25T14:09:54.333 回答
0

我不记得在 c 中使用汇编程序的语义,但通常当您在汇编程序中比较一个数字时,您会将这些数字相减。如果它们是相同的数字,则将设置零位,因此您可以进行条件跳转。请务必使用正确的寄存器来匹配 int 的大小。

非常粗略的示例代码(这不是我的想法,我写汇编程序已经好几年了):

#load value to compare against into BX
#load number to check into AX
CMP AX, BX
JE label

更新:按照@harold 的建议将 SUB 更改为 CMP

于 2013-01-25T14:24:42.203 回答