有没有办法将汇编代码插入C中?

时间:2020-03-05 18:52:59  来源:igfitidea点击:

我记得当初使用旧的borland DOS编译器时,我们可以执行以下操作:

asm {
 mov ax,ex
 etc etc...
}

现在是否有一种半平台独立的方式来执行此操作?我需要进行BIOS调用,因此,如果有一种无需asm代码的方式进行此操作,那对我同样有用。

解决方案

回答

一个好的开始将是阅读这篇有关C / C ++中的内联汇编的文章:

http://www.codeproject.com/KB/cpp/edujini_inline_asm.aspx

文章中的示例:

#include <stdio.h>

int main() {
    /* Add 10 and 20 and store result into register %eax */
    __asm__ ( "movl , %eax;"
                "movl , %ebx;"
                "addl %ebx, %eax;"
    );

    /* Subtract 20 from 10 and store result into register %eax */
    __asm__ ( "movl , %eax;"
                    "movl , %ebx;"
                    "subl %ebx, %eax;"
    );

    /* Multiply 10 and 20 and store result into register %eax */
    __asm__ ( "movl , %eax;"
                    "movl , %ebx;"
                    "imull %ebx, %eax;"
    );

    return 0 ;
}

回答

使用GCC

__asm__("movl %edx, %eax\n\t"
        "addl , %eax\n\t");

使用VC ++

__asm {
  mov eax, edx
  add eax, 2
}

回答

在海湾合作委员会中,不仅仅如此。在指令中,我们必须告诉编译器进行了哪些更改,以便其优化程序不会出错。我不是专家,但有时看起来像这样:

asm ("lock; xaddl %0,%2" : "=r" (result) : "0" (1), "m" (*atom) : "memory");

最好用C编写一些示例代码,然后要求GCC生成程序集列表,然后修改该代码。

回答

非x86 Microsoft编译器不支持嵌入式汇编。我们必须在单独的程序集源文件中定义整个函数,然后将其传递给汇编器。

我们极不可能在受保护模式的操作系统下调用BIOS,并应使用该系统上可用的任何功能。即使我们处于内核模式,也可能不安全,如果这样做,BIOS可能无法正确地就操作系统状态进行同步。