How to detect in runtime if some Compiler Option (like Assertions) was set to ON?

亡梦爱人 提交于 2019-12-10 04:00:04

问题


What is the conditional to check if assertions are active in Delphi?

I would like to be able to do something to suppress hints about unused variables when assertions are not active in code like

procedure Whatever;
var
   v : Integer;
begin
   v := DoSomething;
   Assert(v >= 0);
end;

In the above code, when assertions are not active, there is a hint about variable v being assigned a value that is never used.

The code is in a library which is going to be used in various environments, so I'd be able to test for assertions specifically, and not a custom conditional like DEBUG.


回答1:


You can do this using the $IFOPT directive:

{$IFOPT C+}
  // this block conditionally compiled if and only if assertions are active
{$ENDIF}

So you could re-write your code like this:

procedure Whatever;
{$IFOPT C+}
var
   v : Integer;
{$ENDIF}
begin
   {$IFOPT C+}v := {$ENDIF}DoSomething;
   {$IFOPT C+}Assert(v >= 0);{$ENDIF}
end;

This will suppress the compiler hint, but it also makes your eyes bleed.

I would probably suppress it like this:

procedure SuppressH2077ValueAssignedToVariableNeverUsed(const X); inline;
begin
end;

procedure Whatever;
var
   v : Integer;
begin
   v := DoSomething;
   Assert(v >= 0);
   SuppressH2077ValueAssignedToVariableNeverUsed(v);
end;

The untyped parameter that the suppress function receives is sufficient to suppress H2077. And the use of inline means that the compiler emits no code since there is no function call.



来源:https://stackoverflow.com/questions/16730471/how-to-detect-in-runtime-if-some-compiler-option-like-assertions-was-set-to-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!