Search code examples
delphicompiler-directives

Add unit to project is removing a compiler directive from the project source


Should this work this way or am I doing something wrong?

I have this code in my project source:

  {$IFDEF DEBUG}
  ADebugUnit,
  {$ELSE}
  ARelaseUnit,
  {$ENDIF}

I want ADebugUnit to be used when in debug mode but AReleaseUnit to be used when compiling in release mode. This works great EXCEPT when I select to add a new unit to the project. When I do that it will basically process the code and only keep the unit that pertains to whichever configuration the project is currently set to.

For example, if the configuration is set to Debug then after adding a new unit to my project the above code changes to just:

ADebugUnit,

Or if my configuration is set to Release it will change to the following after adding a new unit:

ARelaseUnit,

I have to always restore it back to the conditional statements after adding a new unit. Is there a way to accomplish this without having the add new unit interfere?


Solution

  • The IDE owns much of the DPR file. Be careful of what you do to it, or you risk exactly what you've observed (or worse — depending on the nature of the changes, the IDE might sometimes decide not to allow the file to be compiled at all!).

    Among other things, what this means is that you cannot conditionally include units in the DPR file. You'll have to find another solution to whatever problem you were trying to solve.

    For example, maybe you could use the unit from somewhere else in your project instead of the DPR file.

    Or maybe you could consolidate the two units into one, and then have its contents conditionally compiled instead.

    Or maybe you could just use the debug code all the time since that increases the chances that you ship the same code you tested.

    Or, if this problem only occurs when you use the "add unit" dialog, you could just forego that dialog and edit the DPR file manually. There's no other magic behind adding a unit to a project, except that the uses clause gets rewritten, as you've noticed.