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?
This question is related to
c++
macros
cross-platform
c-preprocessor
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
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.
Source: Stackoverflow.com