Conditional Compilation in common unit depending from specific project?

荒凉一梦 提交于 2021-01-27 14:13:58

问题


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?


回答1:


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.




回答2:


I am sure this is a duplicate of something but I couldn't find an obvious one explaining the basic concepts. This is explained in the documentation (http://docwiki.embarcadero.com/RADStudio/XE6/en/Conditional_compilation_%28Delphi%29).

You can use {$IFDEF} for this. You check for it with:

{$IFDEF MyValue}
{$ELSE}
{$ENDIF}

or for not defined:

{$IFNDEF MyValue}
{$ELSE}
{$ENDIF}

You then need to define the value. You can do this either in a source file with:

{$DEFINE MyValue}

or in your project options (Project > Options > Delphi Compiler).



来源:https://stackoverflow.com/questions/24127491/conditional-compilation-in-common-unit-depending-from-specific-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!