c++ - 编译 __asm 代码所需的标志

标签 c++ assembly g++

使用内联汇编指令编译代码是否需要任何标志?

我正在尝试让 g++ 编译以下代码(从 SO 上的答案克隆而来):

#include <iostream>

using namespace std;

inline unsigned int get_cpu_feature_flags()
{
    unsigned int features;

    __asm
    {                             // <- Line 10
        // Save registers
        push    eax
        push    ebx
        push    ecx
        push    edx

        // Get the feature flags (eax=1) from edx
        mov     eax, 1
        cpuid
        mov     features, edx

        // Restore registers
        pop     edx
        pop     ecx
        pop     ebx
        pop     eax
    }

    return features;
}

int main() {
    // Bit 26 for SSE2 support
    static const bool cpu_supports_sse2 = (get_cpu_feature_flags() & 0x04000000)!=0;
    cout << (cpu_supports_sse2? "Supports SSE" : "Does NOT support SSE");
}

但我收到以下错误:

$ g++ t2.cpp 
t2.cpp: In function ‘unsigned int get_cpu_feature_flags()’:
t2.cpp:10:5: error: expected ‘(’ before ‘{’ token
t2.cpp:12:9: error: ‘push’ was not declared in this scope
t2.cpp:12:17: error: expected ‘;’ before ‘eax’
$

最佳答案

正如其他人暗示但未明确指出的那样,对于 gcc(它使用基于字符串的 asm("...") 语言而不是真正的内联汇编代码)和 gas(它使用 AT&T 语法代替),这是不正确的语法英特尔语法)。

谷歌搜索“gcc inline assembly”找到了这个教程,看起来不错:

http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html

您可以在此处找到 gcc 文档的相关部分:

http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/Extended-Asm.html

关于c++ - 编译 __asm 代码所需的标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12098593/

相关文章:

c++ - 这些行号在此错误中意味着什么?

c++ - 模板特化 - clang 和 gcc 的不同结果

c++ - gcc 一起构建对象和依赖文件

c++ - 链表查找函数 C++

linux - Linux ARM 上程序寄存器和堆栈的初始状态

c++ - 如何查找并替换存储在 char 数组中的字符串?

Delphi内联汇编器指向结构体的指针

assembly - x86 比较命令目标语法

c++ - 需要有关将双变量发布到 ROS 主题的信息

c++ - 为什么 i = v[i++] 未定义?