Chapter 9. Escaping #ifdef Hell
C is widespread, in particular with systems where high-performance or hardware-near programming is required. With hardware-near programming comes the necessity of dealing with hardware variants. Aside from hardware variants, some systems support multiple operating systems or cope with multiple product variants in the code. A commonly used approach to addressing these issues is to use #ifdef statements of the C preprocessor to distinguish variants in the code. The C preprocessor comes with this power, but with this power also comes the responsibility to use it in a well-structured way.
However, that is where the weakness of the C preprocessor with its #ifdef statements shows up. The C preprocessor does not support any methods to enforce rules regarding its usage. That is a pity, because it can very easily be abused. It is very easy to add another hardware variant or another optional feature in the code by adding yet another #ifdef. Also, #ifdef statements can easily be abused to add quick bug fixes that only affect a single variant. That makes the code for different variants more diverse and leads to code that increasingly has to be fixed for each of the variants
separately.
Using #ifdef statements in such an unstructured and ad-hoc way is the certain path to hell. The code becomes unreadable and unmaintainable, which all developers should avoid. This chapter presents approaches to escape from such a situation or avoid it altogether.
This chapter ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access