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.