Question

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;
Was it helpful?

Solution

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;

OTHER TIPS

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;

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top