Problem
things I only want to provide for one operating system and not for the other Is there a generic #ifdef that may be used?
Something like:
#ifdef LINUX_KEY_WORD
... // linux code goes here.
#elif WINDOWS_KEY_WORD
... // windows code goes here.
#else
#error "OS not supported!"
#endif
Although the question is a repetition, the answers provided here are far superior, particularly the accepted one.
Asked by Sardathrion – against SE abuse
Solution #1
use:
#ifdef __linux__
//linux code goes here
#elif _WIN32
// windows code goes here
#else
#endif
Answered by Muhammad Anjum Kaiser
Solution #2
You can do:
#if MACRO0
//code...
#elif MACRO1
//code...
#endif
…where the identification is:
__linux__ Defined on Linux
__sun Defined on Solaris
__FreeBSD__ Defined on FreeBSD
__NetBSD__ Defined on NetBSD
__OpenBSD__ Defined on OpenBSD
__APPLE__ Defined on Mac OS X
__hpux Defined on HP-UX
__osf__ Defined on Tru64 UNIX (formerly DEC OSF1)
__sgi Defined on Irix
_AIX Defined on AIX
_WIN32 Defined on Windows
Answered by user1527227
Solution #3
Although it is not an answer, it was included in case someone else was looking for the same thing in Qt.
In Qt
QString Get::osName()
{
#if defined(Q_OS_ANDROID)
return QLatin1String("android");
#elif defined(Q_OS_BLACKBERRY)
return QLatin1String("blackberry");
#elif defined(Q_OS_IOS)
return QLatin1String("ios");
#elif defined(Q_OS_MAC)
return QLatin1String("osx");
#elif defined(Q_OS_WINCE)
return QLatin1String("wince");
#elif defined(Q_OS_WIN)
return QLatin1String("windows");
#elif defined(Q_OS_LINUX)
return QLatin1String("linux");
#elif defined(Q_OS_UNIX)
return QLatin1String("unix");
#else
return QLatin1String("unknown");
#endif
}
Answered by Yash
Solution #4
It is dependent on the compiler that is being used.
The Windows definition, for example, can be WIN32 or _WIN32.
Linux can be defined as UNIX, __unix__, LINUX, or __linux__.
Answered by Igor
Solution #5
This comment isn’t about macro war, but rather about throwing an error if no suitable platform can be found.
#ifdef LINUX_KEY_WORD
... // linux code goes here.
#elif WINDOWS_KEY_WORD
... // windows code goes here.
#else
#error Platform not supported
#endif
If #error is not supported, you may use static_assert (C++0x) keyword. Or you may implement custom STATIC_ASSERT, or just declare an array of size 0, or have switch that has duplicate cases. In short, produce error at compile time and not at runtime
Answered by Ajay
Post is based on https://stackoverflow.com/questions/6649936/c-compiling-on-windows-and-linux-ifdef-switch