如何使用预处理程序指令检查操作系统版本(Windows)?

时间:2013-07-07 16:35:50

标签: c++ c operating-system c-preprocessor preprocessor-directive

我想知道是否有机会检查我真正使用的Windows版本。类似于:How do I check OS with a preprocessor directive?的东西。

我尝试了MSDN的代码:

  1. http://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
  2. http://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx
  3. 但是他们中的任何一个都给了我很好的结果(例如:根据http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx,当我在Windows XP上时,我的代码应该打印5.1但它显示了5 ...)

    有没有可靠的方法(我更喜欢预处理程序指令的方式)来找出我正在使用的Windows?

    我的代码:

    #include <windows.h>
    #include <iostream>
    
    int main()
    {
        OSVERSIONINFO osvi;
        BOOL bIsWindowsXPorLater;
    
        ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
        osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    
        GetVersionEx(&osvi);
    
        // I HAD THIS, AND IT WAS WRONG! :<
        std::cout << osvi.dwMajorVersion << "\n";
    
        // CHANGED THE ABOVE LINE TO THE LINE BELOW AND IT IS OK NOW :D
        std::cout << osvi.dwMajorVersion << "." << osvi.dwMinorVersion << "\n";
    
    
        return 0;
    }
    

1 个答案:

答案 0 :(得分:2)

你实际上得到了正确的结果。但是你只打印主要版本:

std::cout << osvi.dwMajorVersion << "\n";

而是尝试使用:

if (osvi.dwMinorVersion >= 1) {
     std::cout << osvi.dwMajorVersion << "." << osvi.dwMinorVersion << std::endl;
} else {
     std::cout << osvi.dwMajorVersion << std::endl;
}