c++operating-system

How do I find the name of an operating system?


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

"Windows" //or
"Unix"

Nothing fancy, I dont need the version numbe or anything. Just the os name. A quick google searc didnt turn up anything useful, so I thought I'd post this here


Solution

  • 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.

    As suggested in the comments, you could also use macros here to have comprehensive solution.