Is it better to use `#ifdef` or inheritance for cross-compiling?

守給你的承諾、 提交于 2019-12-05 07:07:11

Preferably, contain the platform dependant nature of the operations within the methods so the class declaration remains the same across platforms. (ie, use #ifdefs in the implementations)

If you can't do this, then your class ought to be two completely separate classes, one for each platform.

My personal preference is to push ifdef magic into the make files, so the source code stays as clean as possible. Then have an implementation file per platform. This of course implies you can come up with an interface common for all your supported systems.

Edit:

One common way of getting around such a lower denominator design for cross-platform development is an opaque handle idiom. Same idea as ioctl(2) escape route - have a method returning opaque forward-declared structure defined differently for each platform (preferably in the implementation file) and only use it when common abstraction doesn't hold.

If you're fully sure that you won't use functions from the other OS on the one compiled, then using ifdef's has a lot of advantages:

  1. Code and variables non used won't be compiled into the executable (however smart-linking helps here a bit)
  2. It will be ease to see what code is live
  3. You will be able to easily include platform dependent files.

However, classing based on OS can still have it's benefits:

  1. You'll be able to be sure that the code compiles on all platforms when doing changes for one
  2. The code and design will be cleaner

The latter is achieved by ifdefing platform-specific code in the class bodies themselves, or just ifdefing out the non-supported OS instances in compilation.

My preference is to push platform specific issues to the leaf-most modules and try to wrap them into a common interface. Put the specific methods, classes and functions into separate translation units. Let the linker and build process determine which specific translation units to combine. This makes for much cleaner code and easier debugging times.

From experience, I had a project that used #ifdef VERSION2. I spent a week in debugging because one module used #ifdef VERSION_2. A subtlety that would be easier to catch if all the version 2 specific code was in version 2 modules.

Having #ifdefs for platform specific code is idiomatic; especially since code for one platform won't even compile if it's enabled on another. Sounds like a good approach to me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!