2013-01-10 68 views
5

在爲Windows編寫新代碼時,我偶然發現了Windows API的_cpuinfo()。由於我主要處理Linux環境(GCC),我想要訪問CPUInfo。如何在Linux中調用「cpuid」?

我曾嘗試以下:

#include <iostream> 

int main() 
{ 
    int a, b; 

    for (a = 0; a < 5; a++) 
    { 
    __asm ("mov %1, %%eax; "   // a into eax 
      "cpuid;" 
      "mov %%eax, %0;"    // eax into b 
      :"=r"(b)      // output 
      :"r"(a)      // input 
      :"%eax","%ebx","%ecx","%edx" // clobbered register 
     ); 
    std::cout << "The code " << a << " gives " << b << std::endl; 
    } 

    return 0; 
} 

此使用匯編,但我不想重新發明輪子。有沒有其他的方式來實現沒有彙編的CPUInfo?

編譯器錯誤:

[email protected]:~/Desktop/prog$ g++ -Wall CPUInfo.cpp 
CPUInfo.cpp: In function ‘int main()’: 
CPUInfo.cpp:10:22: error: expected ‘)’ before ‘;’ token 
CPUInfo.cpp:10:23: error: expected primary-expression before ‘)’ token 
CPUInfo.cpp:10:23: error: expected ‘;’ before ‘)’ token 
CPUInfo.cpp:8:8: warning: unused variable ‘b’ [-Wunused-variable] 
CPUInfo.cpp:12:8: error: expected ‘}’ at end of input 
+1

所以,這是g ++我猜。和x86?你應該說。無論如何,問題是什麼?你告訴我們你在做什麼,並顯示了代碼。但毫無疑問。 –

+0

@JerryCoffin我正在運行Linux(因爲在這裏將確定執行代碼的計算機的CPU的Linux部分)。我已經在Win API中使用了_cpuinfo()函數的Windows版本/部分。這是我的觀點。 – TheBlueCat

+0

@DavidHeffernan看到我的更新後,我忽略了添加編譯器錯誤。 – TheBlueCat

回答

31

既然你是用gcc編譯,那麼你可以包括cpuid.h其中宣佈這些功能:

/* Return highest supported input value for cpuid instruction. ext can 
    be either 0x0 or 0x8000000 to return highest supported value for 
    basic or extended cpuid information. Function returns 0 if cpuid 
    is not supported or whatever cpuid returns in eax register. If sig 
    pointer is non-null, then first four bytes of the signature 
    (as found in ebx register) are returned in location pointed by sig. */ 
unsigned int __get_cpuid_max (unsigned int __ext, unsigned int *__sig) 

/* Return cpuid data for requested cpuid level, as found in returned 
    eax, ebx, ecx and edx registers. The function checks if cpuid is 
    supported and returns 1 for valid cpuid information or 0 for 
    unsupported cpuid level. All pointers are required to be non-null. */ 
int __get_cpuid (unsigned int __level, 
    unsigned int *__eax, unsigned int *__ebx, 
    unsigned int *__ecx, unsigned int *__edx) 

你並不需要,也不應該,再實現這個功能。

+6

+1不知道該標題存在。我一直在做一些內聯彙編。 – Mysticial

+0

當然。無論如何,我設法讓這部分編譯。儘管如此,爲什麼我不應該重新實施呢?除了節省時間嗎? – TheBlueCat

+1

@Mysticial這是我對GCC和Linux的完全無知派上用場的地方。我不得不穀歌的答案! –

7
for (a =0; a < 5; ++a;) 

那裏應該只有兩個分號。你有三個。

這是基本的C/C++語法; CPUID是一個紅鯡魚。

+0

錯字。我在發佈之前修正了它,因爲某種原因它回到了那裏。我在Git上改變了分支,這可能是原因。但是,我確實知道這個「基本語法」。 – TheBlueCat

+7

但是你發佈的錯誤是由這個錯字造成的。如果您已修復此問題並仍然存在問題,請更新錯誤列表。 – user9876