首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Linux中调用cpuid?

如何在Linux中调用cpuid?
EN

Stack Overflow用户
提问于 2013-01-11 04:33:45
回答 2查看 18.6K关注 0票数 10

在为Windows编写新代码时,我偶然发现了Windows API中的_cpuinfo()。由于我主要处理的是Linux环境(GCC),所以我希望能够访问CPUInfo。

我尝试过以下几种方法:

代码语言:javascript
复制
#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的方法?

编译器错误:

代码语言:javascript
复制
lewis@lewis-desktop:~/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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-11 04:44:08

因为你是用GCC编译的,所以你可以包括cpuid.h,它声明了这些函数:

代码语言:javascript
复制
/* 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)

您不需要也不应该重新实现此功能。

票数 39
EN

Stack Overflow用户

发布于 2013-01-11 04:45:34

代码语言:javascript
复制
for (a =0; a < 5; ++a;)

那里应该只有两个分号。你有三个。

这是基本的C/C++语法;CPUID是在转移注意力。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14266772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档