How to Check Which Operating System with C++
Make your programs portable and easy to implement.
Many times we are developing portable programs with C++ that we need to create a single code that works on different platforms.
And for that we need to use PRE PROCESSING DIRECTIVES:
#if defined(), …
In this case there are specific MACROS for each operating system, for example:
- If you want to detect if the system is Linux, just use the macro:
- If you want to check if it’s Windows, you can use:
Checking if it’s Linux or Windows
Below is an example of C++ code that runs on both operating systems and emits a “Hello, World!” depending on the operating system:
In case of Windows, you can still create another
#if inside to detect if:
_WIN64, this Windows is 64-bit only;
_WIN32, both 64-bit and 32-bit
__CYGWIN__another more modern alternative.
Checking various operating systems
You can still check if it is UNIX type (Linux or BSD, macOS NOT):
For a complete list of all macros for operating systems you can see here.
Using gcc to detect macro names
To have a list of macros you can detect, use
It may be that
clang++also have these options, but I haven’t reinstalled them for testing yet.
- On GNU/Linux:
- On Windows
The output will be extensive:
Small snippet below.