如何在运行时检测某些编译器选项(如断言)是否设置为ON? [英] How to detect in runtime if some Compiler Option (like Assertions) was set to ON?

查看:330
本文介绍了如何在运行时检测某些编译器选项(如断言)是否设置为ON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在断言不是的时候,我希望能够做某些事情来阻止对未使用变量的提示活动在代码如

  procedure Whatever; 
var
v:整数;
begin
v:= DoSomething;
Assert(v> = 0);
结束

在上述代码中,当断言不活动时,有一个关于变量v被分配的提示值是从未使用过的。



代码在一个将用于各种环境的库中,所以我可以专门测试断言,不是像DEBUG那样的自定义条件。

解决方案

您可以使用 $ IFOPT 指令:

  {$ IFOPT C +} 
//仅当断言活动时有条件地编译此块
{$ ENDIF}

所以你可以重写这样的代码:

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

这将抑制编译器提示,但也会使您的眼睛流血。



我可能会这样压制:

  procedure SuppressH2077ValueAssignedToVariableNeverUsed(const X);一致; 
begin
end;

程序无论如何
var
v:整数;
begin
v:= DoSomething;
Assert(v> = 0);
SuppressH2077ValueAssignedToVariableNeverUsed(v);
结束

抑制功能接收的无类型参数足以抑制H2077。而使用 inline 意味着编译器不会发出代码,因为没有函数调用。


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.

解决方案

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.

这篇关于如何在运行时检测某些编译器选项(如断言)是否设置为ON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆