2012-08-23 90 views
3

是否有任何标志需要用内联汇编指令来编译代码?需要编译__asm代码的标志

我试图让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’ 
$ 
+0

这看起来像VC++可以接受的东西(在Windows上)。您可以在[本维基百科文章](http://en.wikipedia.org/wiki/CPUID)中找到各种其他实现。 –

+0

'__asm'是一个VC++扩展。 C++标准汇编语句看起来像'asm(“code here”);'Gcc使用标准格式,并用一些更多的字符串文字扩展它来声明输入,输出和其他约束。 – bames53

回答

5

正如其他人已经暗示但没有明确指出,这是gcc(它使用基于字符串的asm(“...”)语言而不是真正的内联汇编代码)和气体(它使用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

1

这是

__asm(
    //... 
) 

不是

__asm{ 
    //... 
} 

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

+0

谢谢。现在它说't2.cpp:12:9:错误:在'push'之前预期的字符串。还有什么我在这里做错了吗? – Lazer

+0

It * is *'__asm {}'in [Microsoft Visual C++](http://msdn.microsoft.com/en-us/library/45yd4tzz(v = vs.100).aspx) –

+1

@Lazer:Don'不要成为货运邪教程序员。 *了解*你正在写什么以及你为什么写它。从头开始:您想在GCC的代码中包含汇编指令。开始搜索并学会正确地做,而不只是一遍又一遍地猜测。 – GManNickG

0

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

相关问题