Identifying the target platform
←Older revision | Newer revision→
A common problem is identifying the target platform at compile-time so that specific code can be used, perhaps to work around a quirk, or to access a non-standard feature of the target platform.
Standard compiler platform macros
The following table is a partial extract of [Pre-defined C/C++ Compiler Macros], part of a useful resource to compiler macro definitions.
Please update the table carefully with your platform or corrections:
|Platform||Defined macro||Other notes|
|Darwin||DARWIN||Darwin is not necessarily OS X, see below|
|FreeBSD||__FreeBSD__||Consider using the BSD macro|
|Linux||linux or __linux||I also found LINUX|
|MacOS X||__MACOSX__ or __APPLE__|
|NetBSD||__NetBSD__||Consider using the BSD macro|
|OpenBSD||__OpenBSD__||Consider using the BSD macro|
|Solaris||sun or __sun||SunOS versions < 5 will not have __SVR4 or __svr4__ defined|
|Windows||_WIN32 or __WIN32__|
You can use #if wrappers like:
#if defined (__FreeBSD__) ... #elif defined (__linux) || defined (linux) ... #else ... #endif
Using GNUStep-Make's support
Chris Vetter shared a tip on the use of your GNUmakefile.preamble with the following line:
ADDITIONAL_CPPFLAGS += -D$(GNUSTEP_HOST_OS)
and then the #if wrappers will look like:
#if defined( freebsd ) ... #elif defined( netbsdelf ) ... #else ... #endif
To be on the safe side, you may then want to mix the compiler defaults and GNUstep's definitions. It's also good style to add an error or at least a warning in case a particular platform is not (yet) supported.
#if defined( freebsd ) || defined( __FreeBSD__ ) ... #elif defined( darwin ) || defined( DARWIN ) ... #else # error Do not know how to handle this feature on your platform. #endif
Always keep in mind that not everyone is using your preferred platform and that implementations may vary. This is especially true with respect to the implementation and usage of /proc on Linux as compared to other systems.
It's much better generating an error (as mentioned above) than just assuming your code will work on a different platform. The former will most likely get someone involved in your pet project and have them send in patches for their particular system. The latter will probably just annoy people, especially if your code screws up (on) their system due to differences...