c++qtoperating-system

Determine Operating System during compile time


I am new to QT and I am struggling to understand how to determine the operating system before the main function is executed. I am a complete newbie in this area so any guidance would be greatly appreciated.

I would like to determine if the program is running in one of the following environments:

Windows
Unix
Linux
Mac

Also how would I use this data in the main function?

Many thanks


Solution

  • You can use preprocessor definitions to work out what platform the code is being compiled on.

    For example, to check if you're on Windows:

    #if (defined (_WIN32) || defined (_WIN64))
        // windows code
    #endif
    

    For Linux:

    #if (defined (LINUX) || defined (__linux__))
        // linux code
    #endif
    

    ...and so on for each platform you're interested in. This way, code not relevant to the platform you're targeting will be removed.

    Here's an example of some code that uses this:

    #include <iostream>
    
    int main()
    {
        #if (defined (_WIN32) || defined (_WIN64))
            std::cout << "I'm on Windows!" << std::endl;
        #elif (defined (LINUX) || defined (__linux__))
            std::cout << "I'm on Linux!" << std::endl;
        #endif
    }