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?
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.
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.
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.
#if
ask if defined, the others test for value. If would be more consistent to do #elif defined(__unix__)
, etc, I think.
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
Success story sharing
__APPLE__
distinguish between OSX and iOS?__APPLE__
is set for both OS X and iOS. You can#include <TargetConditionals.h>
inside#ifdef __APPLE__
, which then gives you aTARGET_OS_IPHONE #define
.__MINGW64__
is also available when one uses mingw64__MINGW64__
is referenced, think_MSC_VER
for Windows/MSVC is worth a mention (which can also be used to check MSVC Version).