是否需要使用内联汇编指令编译代码?
我试图让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");
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
$ 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’
$
Run Code Online (Sandbox Code Playgroud)
正如其他人暗示但没有明确说明的那样,这是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