How to identify platform/compiler from preprocessor macros?

C++MacrosCross PlatformC Preprocessor

C++ Problem Overview


I'm writing a cross-platform code, which should compile at linux, windows, Mac OS. On windows, I must support visual studio and mingw.

There are some pieces of platform-specific code, which I should place in #ifdef .. #endif environment. For example, here I placed win32 specific code:

#ifdef WIN32
#include <windows.h>
#endif

But how do I recognize linux and mac OS? What are defines names (or etc.) I should use?

C++ Solutions


Solution 1 - C++

For Mac OS:

#ifdef __APPLE__

For MingW on Windows:

#ifdef __MINGW32__

For Linux:

#ifdef __linux__

For other Windows compilers, check this thread and this for several other compilers and architectures.

Solution 2 - C++

See: http://predef.sourceforge.net/index.php

This project provides a reasonably comprehensive listing of pre-defined #defines for many operating systems, compilers, language and platform standards, and standard libraries.

Solution 3 - C++

Here's what I use:

#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
    // Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
    // Unix
#elif __linux__
    // linux
#elif __APPLE__
    // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif

EDIT: Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.

Solution 4 - C++

If you're writing C++, I can't recommend using the Boost libraries strongly enough.

The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.

#include <boost/predef.h>

// ...

#if BOOST_OS_WINDOWS

#elif BOOST_OS_LINUX

#elif BOOST_OS_MACOS

#endif

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArenimView Question on Stackoverflow
Solution 1 - C++karlphillipView Answer on Stackoverflow
Solution 2 - C++John BartholomewView Answer on Stackoverflow
Solution 3 - C++rubenvbView Answer on Stackoverflow
Solution 4 - C++rvalueView Answer on Stackoverflow