3

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

我正在尝试让 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’
$
4

4 回答 4

5

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

谷歌“gcc 内联汇编”拉出了这个教程,看起来不错:

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

于 2012-08-23T19:39:58.637 回答
1

它是

__asm(
   //...
)

不是

__asm{
   //...
}

另外,请注意标准版本是asm.

于 2012-08-23T19:22:48.320 回答
0

对于gcc内联汇编,语法是asm("<instructions>" : "<output constraints>" : "<input constraints>"). 请注意使用括号而不是大括号,并且指令(和可选的约束子句)放置在字符串文字中。

于 2012-08-23T19:42:23.490 回答
0

我发现这种语法特定于 ARM 处理器和 MS asm。看

http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/BABFDCGD.html

如果它是另一个处理器或编译器(如 Keil),请查阅他们的支持页面。

于 2014-02-19T21:41:57.803 回答