Tuesday, 11 February 2014

Conditional Compilation in Delphi

Conditional Compilation in Delphi

Conditional compilation is based on the existence and evaluation of constants, the status of compiler switches, and the definition of conditional symbols.

Conditional symbols work like Boolean variables: they are either defined (true) or undefined (false). Any valid conditional symbol is treated as false until it has been defined. The {$DEFINE} directive sets a specified symbol to true, and the {$UNDEF} directive sets it to false. You can also define a conditional symbol by using the -D switch with the command-line compiler or by adding the symbol to the Conditional Defines field on the Project > Options > Delphi Compiler page.

The conditional directives {$IFDEF}, {$IFNDEF}, {$IF}, {$ELSEIF}, {$ELSE}, {$ENDIF}, and {$IFEND} allow you to compile or suppress code based on the status of a conditional symbol. {$IF} and {$ELSEIF} allow you to base conditional compilation on declared Delphi identifiers. {$IFOPT} compiles or suppresses code depending on whether a specified compiler switch is enabled.

For example, the following Delphi code snippet processes differently depending on whether the DEBUG conditional define is set. You can set conditional defines on the Project > Options > Delphi Compiler page or by entering {$DEFINE DEBUG} in your code:

{$DEFINE DEBUG}
{$IFDEF DEBUG}
  Writeln('Debug is on.');  // This code executes.
{$ELSE}
  Writeln('Debug is off.');  // This code does not execute.
{$ENDIF}

{$UNDEF DEBUG}
{$IFNDEF DEBUG}
  Writeln('Debug is off.');  // This code executes.
{$ENDIF}

Note: Conditional symbols are not Delphi identifiers and cannot be referenced in actual program code. Similarly, Delphi identifiers cannot be referenced in any conditional directives other than {$IF} and {$ELSEIF}.

Note: Conditional definitions are evaluated only when source code is recompiled. If you change a conditional symbol's status and then rebuild a project, source code in unchanged units may not be recompiled. Use Project > Build All Projects to ensure that everything in your project reflects the current status of conditional symbols.

No comments:

Post a Comment