humancode.us

Writing Multiplatform Code

April 6, 2018

When writing multi-platform code, conditionalize code on features, not platforms. For example, if you can’t use instruction set X on platform A, conditionalize on HAS_FEATURE_X instead of IS_PLATFORM_A.

Then, create one file in which you map platforms to features. That way you can easily add new platforms and switch features on and off without going through all your code.

#if IS_PLATFORM_A
  #define HAS_FEATURE_X 0
  #define HAS_FEATURE_Y 1
#elif IS_PLATFORM_B
  #define HAS_FEATURE_X 1
  #define HAS_FEATURE_Y 0
#else
  // Default behavior, should work on all platforms
  #define HAS_FEATURE_X 0
  #define HAS_FEATURE_Y 0
#endif

Remember, if you have a final #else clause, it should only contain platform-independent code that will work on any platform, perhaps with less optimization.