Search code examples
delphiuses-clause

How do include something if no defines are found


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;

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;