Introduction

Understand conditional compilation and the features of D that are specifically for conditional compilation.

We'll cover the following

Conditional compilation

Conditional compilation is for compiling parts of programs in special ways depending on certain compile time conditions. Sometimes, entire sections of a program may need to be taken out and not compiled at all.

Conditional compilation involves condition checks that are evaluable at compile time. Runtime conditional statements like if, for, and while are not conditional compilation features.

We have already encountered some features that can be seen as conditional compilations in the previous chapters, including:

  • unittest blocks are compiled and run only if the -unittest compiler switch is enabled.

  • The contract programming blocks in, out, and invariant are activated only if the -release compiler switch is not enabled.

Unit tests and contracts are about program correctness; whether they are included in the program should not change the behavior of the program. The following are the features of D that are specifically for conditional compilation:

  • debug

  • version

  • static if

  • isexpression

  • __traits

We will see these features one by one in this chapter.


Get hands-on with 1200+ tech skills courses.