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: #ifdef
, #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:
__linux__
; - If you want to check if it’s Windows, you can use:
_WIN32
.
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.
Example:
Checking various operating systems
You can still detect all operating systems. Below is another example that not only detects Linux and Windows, but also checks if it is: macOS, FreeBSD, Android:
You can still check if it is UNIX type (Linux or BSD, macOS NOT): unix
, __unix
or __unix__
.
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 gcc
or g++
:
It may be that
clang
andclang++
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.
References
- https://stackoverflow.com/questions/142508/how-do-i-check-os-with-a-preprocessor-directive
- https://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor
- https://sourceforge.net/p/predef/wiki/OperatingSystems/
Comments