Arenim
Arenim

Reputation: 4237

How to identify platform/compiler from preprocessor macros?

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?

Upvotes: 130

Views: 134996

Answers (4)

rubenvb
rubenvb

Reputation: 76519

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.

Upvotes: 49

rvalue
rvalue

Reputation: 2762

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

Upvotes: 24

karlphillip
karlphillip

Reputation: 93410

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.

Upvotes: 151

John Bartholomew
John Bartholomew

Reputation: 6586

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.

Upvotes: 68

Related Questions