C++ 如何完全禁用对 assert() 的调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5354314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I completely disable calls to assert()?
提问by Abruzzo Forte e Gentile
My code is full of calls to assert(condition)
.
In the debug version I use g++ -g
which triggers my assertions.
Unexpectedly, the same assertions are also triggered in my release version, the one compiled without -g
option.
我的代码充满了对assert(condition)
. 在我使用的调试版本中g++ -g
,它触发了我的断言。出乎意料的是,在我的发布版本中也触发了相同的断言,即没有-g
选项编译的版本。
How can I completely disable my assertions at compile time? Should I explicitly define NDEBUG
in any build I produce regardless of whether they are debug, release or anything else?
如何在编译时完全禁用我的断言?我是否应该NDEBUG
在我生成的任何构建中明确定义,而不管它们是调试、发布还是其他任何东西?
回答by GWW
You must #define NDEBUG
(or use the flag -DNDEBUG
with g++) this will disable assert as long as it's defined before the inclusion of the assert header file.
您必须#define NDEBUG
(或使用-DNDEBUG
带有g++的标志)这将禁用断言,只要它是在包含断言头文件之前定义的。
回答by Prasoon Saurav
Use #define NDEBUG
用 #define NDEBUG
7.2 Diagnostics
1 The header de?nes the assertmacro and refers to another macro,
NDEBUG
which is not de?ned by
<assert.h>
. If NDEBUGis de?ned as a macro name at the point in the source ?le where is included, the assertmacro is de?ned simply as
#define assert(ignore) ((void)0)
The assertmacro is rede?ned according to the current state of NDEBUGeach time that
<assert.h>
is included.
7.2 诊断
1 头文件定义了assert宏并引用了另一个宏,
调试
哪个不是由 定义的
<assert.h>
。如果NDEBUG在源文件中包含的点处定义为宏名称,则断言宏定义为
#define assert(ignore) ((void)0)
该断言宏是雷德?根据当前状态定义NDEBUG每个时间
<assert.h>
被包括。
回答by dcn
You can either disable assertions completely by
您可以通过以下方式完全禁用断言
#define NDEBUG
#include <assert.h>
or you can set NDEBUG (via -DNDEBUG) in your makefile/build procedure depending on whether you want a productive or dev version.
或者你可以在你的 makefile/build 过程中设置 NDEBUG(通过 -DNDEBUG),这取决于你想要一个生产版本还是开发版本。
回答by Alnitak
The -g
flag doesn't affect the operation of assert
, it just ensures that various debugging symbols are available.
该-g
标志不影响 的操作assert
,它只是确保各种调试符号可用。
Setting NDEBUG
is the standard (as in official, ISO standard) way of disabling assertions.
设置NDEBUG
是禁用断言的标准(如官方的 ISO 标准)方式。
回答by Fred Foo
Yes, define NDEBUG
on the command line/build system with the preprocessor/compiler option -DNDEBUG
.
是的,NDEBUG
使用预处理器/编译器选项在命令行/构建系统上定义-DNDEBUG
。
This has nothing to do with the debugging info inserted by -g
.
这与插入的调试信息无关-g
。