Search code examples
delphidelphi-xe2conditional-compilation

Conditional Compilation in common unit depending from specific project?


In Delphi XE2, I have a unit MyUnit.pas which is used by two different projects ProjectA and ProjectB.
MyUnit contains a statement DoSomething; (which is a procedure implemented in an other unit OtherUnit.pas).
Now I want to use Conditional Compilation to include DoSomething only in ProjectA compilation and not in ProjectB compilation, so to avoid ProjectB including/compiling OtherUnit.pas indirectly.
This MUST be Conditional Compilation, as a simple if/else statement obviously does not work for this purpose.
How can this be achieved?


Solution

  • You need to define a conditional in one project, but not the other. For instance, you might define CanUseOtherUnit in the project options for project A, but not for project B.

    Then you need to make the following changes to MyUnit.pas.

    Put the uses clause that refers to OtherUnit inside an $IFDEF:

    uses
      ... {$IFDEF CanUseOtherUnit}, OtherUnit{$ENDIF};
    

    And then at the point where you call the function, again wrap the call inside an $IFDEF:

    {$IFDEF CanUseOtherUnit}
    DoSomething;
    {$ENDIF}
    

    Because the conditional is not defined in project B the compiler ignores the code inside the $IFDEF directives.


    When you actively desire for a unit not to be used, the convenience of search paths becomes a weakness. It's just too easy for you to add units to the program without realising it. When you do not use search paths, and are compelled to add the source files to the project (.dpr file) then you cannot accidentally take a new dependency.