Conditional Compiling |
Top Previous Next |
Conditional compiling simply stated is excluding or including portions of code from your source file based on one or more conditions. Similar to a conditional statement controlling the flow of execution of program statements. The preprocessor is a part of the compiler that scans your source code before the actual compiling to assembly language begins. Among many other tasks the preprocessors looks for conditional compiling statements to determine what should be included in the final executable. This is done by defining conditional identifiers that can be tested anywhere in your code.
Creating a conditional identifier A conditional identifier is a word or sequence of letters and numbers that you want to define as TRUE to the preprocessor. Think of them as a constant without any real value. They are only visible to the preprocessor and are created with the $DEFINE statement. For example suppose you have two versions of your program, a trial version and a paid for version. Maintaining two separate projects would be a solution but its much easier to write the source so you can quickly compile one or the other. $DEFINE TRIAL_VERSION Would define the identifier TRIAL_VERSION as TRUE to the preprocessor. The $DEFINE statement can also be used to create constants. See Constants and Literals for details.
Excluding or including code to be compiled Using the preprocessor commands $IFDEF, $IFNDEF, $ELSE and $ENDIF you can test for a conditional identifier and include or exclude any section of code necessary. Using the identifier from above: $IFDEF TRIAL_VERSION It is important to note that the preprocessor statements are not actually program statements but control what the compiler processes. In our hypothetical trial version/full version code above if the identifier TRIAL_VERSION has been defined then a registration dialog would be shown and saving files disabled. The code to show the welcome dialog is skipped entirely and would not generate any machine code in the executable. Conditional compiling statements can be nested to allow for advanced situations. Continuing with our hypothetical trial version and we wanted to maintain debugging code in the source: $IFDEF TRIAL_VERSION For situations where you only need a negative test just use $IFNDEF $IFNDEF DEBUG
Notes on conditional compiling The $DEFINE statement is source file level meaning that if your using a project the identifier is only defined in the source file the $DEFINE statement appears in. To define a preprocessor identifier across the entire project use an include file and $INCLUDE that file at the beginning of every source file. Everything is skipped if the condition is false. This includes variable definitions, DECLARE statements, etc. If your program depends on a variable or DECLARE statement regardless of the condition then be sure to define them outside of the $IFDEF block. $IFDEF and $IFNDEF can also check for the existence of a constant. |