delphiconditional-compilation

(Delphi) Check state of a switch directive in the function caller's environment


I know that I can check the current state of Delphi's switch directives using this construct:

{$IFOPT R+}
      Writeln('Compiled with range-checking');
{$ENDIF}

Since I'm lacking of in-depth sources on how the Delphi backend compiler works, I'm not sure wether there is a way of changing the behaviour of a function depending on the state of a switch directive at the code line calling it. It'll look something like this:

procedure P1;
begin  
    {$I+}
    P3; 
    {$I-}
end;

// ** state of I unknown

procedure P2;
begin
    {$I-}   
    P3; 
    {$I+}
end;

// ** state of I unknown

procedure P3;
begin       
    // Something like {$IFOPT I+}, but at the state P3 is called
    DoThis;
    {$ELSE}
    DoThat
    {$ENDIF}
end; 

I'm writing adapters for legacy code which I'd urgently like to be untouched. P3 doesn't need to use directives, but I figured this to be the way to go.


Solution

  • Change your Programm like this

    procedure P1;
    begin  
        {$I+}
        P3(true); 
        {$I-}
    end;
    
    procedure P2;
    begin
        {$I-}       
        P3(false); 
        {$I+}
    end;
    
    // ** state of I unknown, but the parameter know the state
    
    procedure P3(WIthRangeCheck: Boolean);
    begin       
        if WIthRangeCheck then
           DoThis
        else
           DoThat;
    end;