1

非常不言自明的代码。为什么它不起作用!

#include <stdio.h>

int main() {
    __asm__("number dw 0"); // declare number?
    printf("%d",number);
    __asm__("mov %eax,number"
            "inc %eax"
            "mov number,%eax");
    printf("%d",number);
    return 0;
}

cc     ex1.c   -o ex1
ex1.c: In function ‘main’:
ex1.c:22:17: error: ‘number’ undeclared (first use in this function)
ex1.c:22:17: note: each undeclared identifier is reported only once for each function it appears in
make: *** [ex1] Error 1

谢谢。

我有很多知识空白要填补...... gcc 手册让我对内联汇编感到困惑,谷歌的教程结果也是如此......

在英特尔 i7 处理器上工作

4

1 回答 1

5

C使用此语法,您可以访问从内联程序集中声明的变量

#include <stdio.h>

int main() {
    int number = 0;
    printf("%d\n",number);
    asm(
        "mov %[number],%%eax\n"
        "inc %%eax\n"
        "mov %%eax,%[number]\n"
        : [number] "=m" (number) : "m" (number) : "eax", "cc" );
    printf("%d\n",number);
    return 0;
}

您可以通过在输入上指定约束让编译器为您加载number到寄存器中eax"a"

#include <stdio.h>

int main() {
    int number = 0;
    printf("%d\n",number);
    asm(
        "inc %%eax\n"
        "mov %%eax,%[number]\n"
        : [number] "=m" (number) : "a" (number) : "cc" );
    printf("%d\n",number);
    return 0;
}

由于 x86inc指令可以直接对内存进行操作,因此您可以将其简化为

#include <stdio.h>

int main() {
    int number = 0;
    printf("%d\n",number);
    asm(
        "incl %[number]\n" /* incl -> "long" (32-bits) */
        : [number] "=m" (number) : "m" (number) : "cc" );
    printf("%d\n",number);
    return 0;
}

有关更多信息,请参阅 gcc 文档:

6.41 带有 C 表达式操作数的汇编器指令

于 2012-10-24T02:18:38.487 回答