【问题标题】:Detect system architecture (x86/x64) while running在运行时检测系统架构 (x86/x64)
【发布时间】:2010-12-10 20:27:33
【问题描述】:

是否可以在程序 在 c++ 中运行(在 windows 和 linux 下)时检测系统/处理器架构?

【问题讨论】:

  • 您知道,如果您在 x86 中编译,它无论如何都会在 x64 CPU 上以 x86 模式运行,对吧?只是检查。
  • 是的,我知道。这就是我想做的。但我想知道架构。
  • @Amit:你是对的。这很好用。

标签: c++ architecture system cpu processor


【解决方案1】:

在 Windows 上,您可以使用 __cpuid。在 Linux 上,您可以open("/proc/cpuinfo") 并查看它。

这是一个基于 MSDN 页面中的示例的 Windows 示例:

#include <intrin.h>

bool cpuSupports64()
{
    int CPUInfo[4];
    __cpuid(CPUInfo, 0);
    return (CPUInfo[3] & 0x20000000) || false;
}

【讨论】:

  • /proc/cpuinfo 没有任何明确的字大小信息。
  • @Amit:clflush size 呢?
  • @Hosam Aly:谢谢。我不知道。 'clflush' 是什么意思?
  • 你能举个例子说明如何在windows中做到这一点吗?
  • 哦,好吧。在我的 32 位操作系统和 32 位硬件上,cflush 大小仍然是 64!
【解决方案2】:

在 Linux 下,您可以使用uname 系统调用。它填充了这个用户分配的结构:

  struct utsname {
           char sysname[];    /* Operating system name (e.g., "Linux") */
           char nodename[];   /* Name within "some implementation-defined
                                 network" */
           char release[];    /* OS release (e.g., "2.6.28") */
           char version[];    /* OS version */
           char machine[];    /* Hardware identifier */
       #ifdef _GNU_SOURCE
           char domainname[]; /* NIS or YP domain name */
       #endif
       };

machine 字段将标识架构。

【讨论】:

    【解决方案3】:

    根据您打算如何处理此信息(例如,为特定 CPU 选择最快的手工编码汇编代码),在 Linux 下您可能需要阅读 /proc/cpuinfo,特别是:“flags”部分,这样您就可以在 SSE/SSE2 实施与 MMX 实施与其他实施之间进行选择。

    Big endian system vs little endian system稍微复杂一些,参考:http://en.wikipedia.org/wiki/Endianess

    【讨论】:

      【解决方案4】:

      您还可以使用处理器宏来检测 c++ 代码中的系统架构,例如:

      #include <iostream>
      
      int main()
      {
      #ifdef __x86_64__
          std::cout << "x86" << std::endl;
      #endif
      
      #ifdef __arm__
          std::cout << "arm" << std::endl;
      #endif
      }
      

      这是Pre-defined Compiler Macros的参考列表。

      编辑:处理器宏与编译器无关,不同的编译器有不同的处理器宏,因此无法通过这种方式检测系统架构。

      【讨论】:

      • 这也是在编译时,而不是在运行时。所以它根本没有回答这个问题
      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 2011-01-08
      • 1970-01-01
      相关资源
      最近更新 更多