0

I use the following code in my settings classes to determine what to use. But now I have run in to the problem that I had forgotten to copy the correct .INC file to my project folder and that give me an AV since none of the defines are found. How do I make sure that if none of the defines are found then U_SettingsConnIni are always in the uses section

 uses
  Dialogs, Forms, SysUtils,
{$IFDEF SETTINGSINI}
  U_SettingsConnIni,
{$ENDIF}
{$IFDEF SETTINGSREG}
  U_SettingsConnReg,
{$ENDIF}
{$IFDEF SETTINGSXML}
  U_SettingsConnXml,
{$ENDIF}
  U_SectionNames;
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
OZ8HP
  • 1,443
  • 4
  • 31
  • 61
  • 2
    If only one define will be specified at a time, use [`IF..ELSE`](http://docwiki.embarcadero.com/RADStudio/XE3/en/IF_directive_(Delphi)). – TLama Aug 23 '13 at 15:54

3 Answers3

3

Just like ordinary if blocks, $ifdef compiler directives support $else. Furthermore, they can be nested.

uses
  Dialogs, Forms, SysUtils,
{$IFDEF SETTINGSREG}
  U_SettingsConnReg,
{$ELSE}
  {$IFDEF SETTINGSXML}
  U_SettingsConnXml,
  {$ELSE}
  U_SettingsConnIni,
  {$ENDIF}
{$ENDIF}
  U_SectionNames;
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
3

This is a scenario better suited to the more powerful $IF than the rather limited $IFDEF.

uses
  Dialogs, Forms, SysUtils,
{$IF Defined(SETTINGSREG)}
  U_SettingsConnReg,
{$ELSEIF Defined(SETTINGSXML)}
  U_SettingsConnXml,
{$ELSE}
  U_SettingsConnIni,
{$IFEND}
  U_SectionNames;

In the latest versions of Delphi you can use $ENDIF here rather than $IFEND if you prefer.

If you want to fail if no conditional is defined, you can do this:

uses
  Dialogs, Forms, SysUtils,
{$IF Defined(SETTINGSREG)}
  U_SettingsConnReg,
{$ELSEIF Defined(SETTINGSXML)}
  U_SettingsConnXml,
{$ELSEIF Defined(SETTINGSINI)}
  U_SettingsConnIni,
{$ELSE}
  {$Message Fatal 'Settings file format conditional must be defined'}
{$IFEND}
  U_SectionNames;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

An alternative method (not exactly answering your question), if you know that one of the defines is required, is to make sure that the compilation fails. In your case that would be:

{$IFNDEF SETTINGSINI}
{$IFNDEF SETTINGSREG}
{$IFNDEF SETTINGSXML}
This line does not compile
{$ENDIF}
{$ENDIF}
{$ENDIF}

That way if none of the conditional defines is set, the compiler will choke on This line does not compile.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jan Doggen
  • 8,799
  • 13
  • 70
  • 144
  • that should have been my next question - how to check if none of the defines have been set. – OZ8HP Aug 23 '13 at 20:38