c – 如何在Linux中调用“cpuid”?

前端之家收集整理的这篇文章主要介绍了c – 如何在Linux中调用“cpuid”?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在为 Windows编写新代码时,我偶然发现了Windows API中的_cpuinfo().因为我主要处理 Linux环境(GCC),所以我希望能够访问cpuInfo.

我尝试过以下方法

  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5. int a,b;
  6.  
  7. for (a = 0; a < 5; a++)
  8. {
  9. __asm ( "mov %1,%%eax; " // a into eax
  10. "cpuid;"
  11. "mov %%eax,%0;" // eax into b
  12. :"=r"(b) // output
  13. :"r"(a) // input
  14. :"%eax","%ebx","%ecx","%edx" // clobbered register
  15. );
  16. std::cout << "The code " << a << " gives " << b << std::endl;
  17. }
  18.  
  19. return 0;
  20. }

这使用组件,但我不想重新发明轮子.有没有其他方法可以在没有汇编的情况下实现cpuInfo?

编译器错误

  1. lewis@lewis-desktop:~/Desktop/prog$g++ -Wall cpuInfo.cpp
  2. cpuInfo.cpp: In function int main()’:
  3. cpuInfo.cpp:10:22: error: expected ‘)’ before ‘;’ token
  4. cpuInfo.cpp:10:23: error: expected primary-expression before ‘)’ token
  5. cpuInfo.cpp:10:23: error: expected ‘;’ before ‘)’ token
  6. cpuInfo.cpp:8:8: warning: unused variable b [-Wunused-variable]
  7. cpuInfo.cpp:12:8: error: expected ‘}’ at end of input

解决方法

由于您正在使用GCC进行编译,因此您可以包含声明这些函数cpuid.h:
  1. /* Return highest supported input value for cpuid instruction. ext can
  2. be either 0x0 or 0x8000000 to return highest supported value for
  3. basic or extended cpuid information. Function returns 0 if cpuid
  4. is not supported or whatever cpuid returns in eax register. If sig
  5. pointer is non-null,then first four bytes of the signature
  6. (as found in ebx register) are returned in location pointed by sig. */
  7. unsigned int __get_cpuid_max (unsigned int __ext,unsigned int *__sig)
  8.  
  9. /* Return cpuid data for requested cpuid level,as found in returned
  10. eax,ebx,ecx and edx registers. The function checks if cpuid is
  11. supported and returns 1 for valid cpuid information or 0 for
  12. unsupported cpuid level. All pointers are required to be non-null. */
  13. int __get_cpuid (unsigned int __level,unsigned int *__eax,unsigned int *__ebx,unsigned int *__ecx,unsigned int *__edx)

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

猜你在找的C&C++相关文章