R – (Delphi) Check state of a switch directive in the function caller’s environment

compiler-constructionconditional-compilationdelphi

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.

Best Answer

No, there's no simple way to do that. Compiler directives operate on a different level than code compilation, and they don't pass meaningful information about their state into the code, and they certainly don't apply outside of their own scope. If you want to pass data to a procedure, the only way to do it is to use a variable, either an argument or a global.

Related Topic