Alex Rivera | Logout

Dos and Don'ts of Conditional Compile

Asked 2010-12-17T10:36:54.827
12

When is doing conditional compilation a good idea and when is it a horribly bad idea?

By conditional compile I mean using #ifdefs to only compile certain bits of code in certain conditions. The #defineds themselves may be in either a common header file or introduced via the -D compiler directive.

Edit
Report

2 Answers

0

Good/justifiable uses are based on cost/benefit analysis. Obviously, people here are very conscious of the risks:

  • in linking objects that saw different versions of classes, functions etc.
  • in making code hard to understand, test and reason about

But, there are uses which often fall into the net-benefit category:

  • header guards
  • code customisations for distinct software "ecosystems", such as Linux versus Windows, Visual C++ versus GCC, CPU-specific optimisations, sometimes word size and endianness factors (though with C++ you can often determine these at compile via template hackery, but that may prove messier still) - abstracts away lower-level differences to provide a consistent API across those environments
  • interacting with existing code that uses preprocessor defines to select versions of APIs, standards, behaviours, thread safety, protocols etc. (sad but true)
  • compilation that may use optional features when available (think of GNU configure scripts and all the tests they perform on OS interfaces etc)
  • request that extra code be generated in a translation unit, such as adding main() for a standalone app versus without for a library
  • controlling code inclusion for distinct logical build modes such as debug and release
answered 2010-12-17T11:52:21.900
-4

It is always a bad idea. What it does is effectively create multiple versions of your source code, all of which need to be tested, which is a pain, to say the least. Unfortunately, like many bad things it is sometimes unavoidable. I use it in very small amounts when writing code that needs to be ported between Windows and Linux, but if I found myself doing it a lot, I would consider alternatives, such as having two separate development sub-trees.

answered 2010-12-17T10:39:57.573

Your Answer