Mega Code Archive

 
Categories / Delphi / Compiler Directives
 

$ifdef - executes code if a conditional symbol has been defined

{$IfDef Symbol} ... Code to run when the symbol is defined ... {$Else} ... Code to run when the symbol is not defined ... {$EndIf} Description The $IfDef compiler directive starts a section of conditionally compiled code. Only if the specified Symbol has been defined. Symbols come in two types. Predefined in Delphi, such as Console when running a console application. And defined by the $Define compiler direcctive. $IfDef is very useful when developing code, allowing various sections to be compiled when testing. Related commands $Define Defines a compiler directive symbol - as used by IfDef $Else Starts the alternate section of an IfDef or IfNDef $EndIf Terminates conditional code compilation $IfNDef Executes code if a conditional symbol has not been defined $IfOpt Tests for the state of a Compiler directive $UnDef Undefines a compiler directive symbol - as used by IfDef Example code : Setting up and using a test mode symbol var text : string; begin // Set our code into test mode {$Define TESTMODE} text := 'We are in test mode'; // Display the value of text if we are in test mode {$IfDef TESTMODE} ShowMessage('text = '+text); {$EndIf} // Switch off test mode {$UnDef TESTMODE} // Display the value of text if we are in test mode {$IfDef TESTMODE} ShowMessage('text = '+text); {$Else} ShowMessage('Out of test mode now'); {$EndIf} end; Show full unit code We are in test mode Out of test mode now