delphidelphi-xe2conditional-compilationdelphi-units

Can I define conditionals in a unit and use them in other units?


I am working on a large unit, the unit got so large that I decided to split it into 3 units. Let's say these unit names are Main, Common, and Objects. The Main unit uses both the other two units, and the Objects unit also uses the Common unit. There is code in all 3 units which needs to refer to these conditionals.

The problem is, no matter which of the 3 units I define these conditionals in, the other 2 units don't see them. I certainly don't want to copy them in all 3 units. I also don't want to define them in the project, because these units will be used by multiple projects, in which case all projects using this shouldn't care about the conditionals.

Can I define these conditionals in a way that all 3 units will see them, without defining them in the project?


Solution

  • Your only option, for conditional defines, is to put them in a .inc file which you then include in all three units.

    However, conditional defines, and $IFDEF are not the only way to achieve conditional compilation. You might consider using a boolean constant instead of a conditional. So long as it is visible in all three units, you can use $IF rather than $IFDEF.

    {$IF MyConstant}
      ....
    {$IFEND}
    

    Or, starting in XE3, you can terminate the {$IF} with {$ENDIF}.

    Personally I tend to favour this latter approach when trying to compile conditionally and don't want the condition to have global scope.