Conditional Compilation

Delphi has a nice assortment of compiler directives that can be used to implement conditional compilation. Conditional compilation enables you to keep a single code base and only compile certain sections of the code, based on various conditions. Conditional symbols work like Boolean values. In conditional compilation, you test if a symbol is defined or undefined. This is achieved with the $IFDEF compiler directive. The conditional block has to finish with the $ENDIF directive. The following procedure will display a message only if you run it on a Linux computer:

{$IFDEF LINUX} WriteLn('Linux'); {$ENDIF}

If you want to make sure that procedures and functions marked with the inline directive can be recompiled with older Delphi compilers, you should include the inline directive in the compilation process only if you're using the Delphi 2005 compiler or a newer one.

To determine if you're using the Delphi 2005 compiler, write this:

{$IFDEF VER170} // Delphi 2005 specific code {$ENDIF}

The VER180 constant indicates the current compiler, and the VER170 constant indicates the Delphi 2005 compiler. Versions 1.0 to 7.0 are Turbo Pascal versions, 8.0 to 15.0 are Delphi versions 1.0 to 7.0, and version 16.0 is Delphi 8 for the .NET framework.

So, if you want to make sure that the compilation will not fail in older compiler versions because of the inline directive, write something like this:

function MyAbs(I: Integer): Integer; {$IFDEF VER170} inline; {$ENDIF}

The above line of code will use the inline directive only in Delphi 2005. To use the inline directive in both Delphi 2005 and newer versions, you can also use the RTLVersion constant and the $IF compiler directive (see Listing 5-17).

Listing 5-17: Using the RTLVersion constant to determine the compiler

image from book
program Project1; {$APPTYPE CONSOLE} var   x: Integer; function MyAbs(I: Integer): Integer;   {$IF RTLVersion >= 17} inline; {$IFEND} begin   if I < 0 then     Result := -I   else     Result := I; end; begin   x := MyAbs(-20);   WriteLn(x);   ReadLn; end.
image from book

Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: