How do I find the name of an operating system?

前端 未结 2 1568
广开言路
广开言路 2021-02-07 13:41

The questions pretty simple. I want want a function (C++) or method which will, on call, returun something like

\"Windows\" //or
\"Unix\"

Noth

相关标签:
2条回答
  • 2021-02-07 13:51

    Since you can not have a single binary file which runs over all operating systems, and you need to re-compile your code again. It's OK to use MACROs.

    Use macros such as

    _WIN32
    _WIN64
    __unix
    __unix__
    __APPLE__
    __MACH__
    __linux__
    __FreeBSD__
    

    like this

    std::string getOsName()
    {
        #ifdef _WIN32
        return "Windows 32-bit";
        #elif _WIN64
        return "Windows 64-bit";
        #elif __APPLE__ || __MACH__
        return "Mac OSX";
        #elif __linux__
        return "Linux";
        #elif __FreeBSD__
        return "FreeBSD";
        #elif __unix || __unix__
        return "Unix";
        #else
        return "Other";
        #endif
    }                      
    

    You should read compiler's manuals and see what MACROS they provided to detect the OS on compile time.

    0 讨论(0)
  • 2021-02-07 14:07

    From the Poco source code:

    Win32:

    std::string EnvironmentImpl::osNameImpl()
    {
        OSVERSIONINFO vi;
        vi.dwOSVersionInfoSize = sizeof(vi);
        if (GetVersionEx(&vi) == 0) throw SystemException("Cannot get OS version information");
        switch (vi.dwPlatformId)
        {
        case VER_PLATFORM_WIN32s:
            return "Windows 3.x";
        case VER_PLATFORM_WIN32_WINDOWS:
            return vi.dwMinorVersion == 0 ? "Windows 95" : "Windows 98";
        case VER_PLATFORM_WIN32_NT:
            return "Windows NT";
        default:
            return "Unknown";
        }
    }
    

    Unix:

    std::string EnvironmentImpl::osNameImpl()
    {
        struct utsname uts;
        uname(&uts);
        return uts.sysname;
    }
    
    0 讨论(0)
提交回复
热议问题