How to Detect Operating system using C++

In this tutorial, we will learn how to detect operating systems using C++. Detecting operating systems is a common requirement when you develop a cross-platform project that’s why today we learn how to detect the operating system using C++.

Detect Operating system using C++

#include <iostream>

#if defined(_WIN32)
const std::string OS = "Windows";
#elif defined(__APPLE__)
const std::string OS = "Mac OS";
#elif defined(__linux__)
const std::string OS = "Linux";
#elif defined(__unix__) 
const std::string OS = "Unix";
#else
const std::string OS = "Other";
#endif

int main() {
    std::cout << "Operating System: " << OS << std::endl;
    return 0;
}

 

Output:- 

Operating System: Windows

Explanation:-

#if defined(_WIN32) it is used for windows.

#elif defined(__APPLE__) it is used for MAC OS.

#elif defined(__linux__)  it is used for Linux.

#elif defined(__unix__) it is used for Unix.

here we used these 4 macros and when the code detect the OS that macors are activated and shows in output.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top