如何在发布模式下自动注释行?
我需要仅在调试模式下“活动”一些代码行,并在发布模式下忽略它们。 有没有办法做这样的事情:
#include <iostream>
using namespace std;
#ifdef _TEST_
#define _cerr cerr
#else
#define _cerr // cerr
#endif
int main() {
_cerr << "TEST message" << endl;
}
这样,当未定义 _TEST_
时,某些行会被注释或从代码中删除。我知道注释是在其余部分之前处理的,所以这段代码是错误的。但是,如何在不显式使用 #ifdefs 的情况下获得我需要的行为呢?
I need to have some lines of code "active" in debug mode only, and ignored in release mode.
Is there a way to do something like this:
#include <iostream>
using namespace std;
#ifdef _TEST_
#define _cerr cerr
#else
#define _cerr // cerr
#endif
int main() {
_cerr << "TEST message" << endl;
}
So that when _TEST_
is not defined, some lines are commented, or removed from the code. I know that comments are processed before the rest, so this code is wrong. But how can I get the behaviour I need without using #ifdefs explicitely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
如果您想要的是在发布版本中删除的调试日志记录,您可以执行以下操作:
If what you are after is debug logging which is removed in release builds, you can do something like:
使用这个:
Use this:
ifdefs 是可行的方法。您还如何知道编译器是否处于发布模式与调试模式?除了在预处理阶段之外,还有什么时候会进行传达?您可以在什么其他阶段决定删除/添加代码(除了在模板生成期间)。嘿,也许我们可以使用模板生成...但是您仍然必须以某种方式关闭 ifdef 来控制您的模板。
也许有一种我没有想到的非常巧妙的方法来做到这一点,但每个人都知道/使用 ifdefs 来达到这个目的。如果你给他们扔一个曲线球,只会大大增加维护代码的人力成本。
坚持使用 ifdef。
ifdefs are the way to go. How else would you know if the compiler is in release vs debug mode? When else besides during the preprocessing stage would that be communicated? At what other stage could you decide to remove/add code (besides during template generation). Hey maybe we can use template generation... but you still have to key off the ifdef somehow to control your template.
Maybe there's a really slick way to do this that I'm not thinking of, but everyone knows/uses ifdefs for this purpose. If you throw them a curveball its only going to drastically increase the human cost of maintaining your code.
Stick with ifdefs.
这里基本上满足了您的要求:
但是,如果您收到编译器关于不明确的
else
的警告,如果您编写如下内容,请不要感到惊讶:您应该始终意识到这一事实
_cerr
实际上是一个不平凡的宏。This here basically does what you are asking for:
But don't be surprised if you for example get compiler warnings about ambiguous
else
if you write something like this:You should always be aware of the fact that this
_cerr
is in fact a non-trivial macro.将 _cerr 定义为空将使编译失败。您可以改为定义一个在发布模式下排除的宏。
例如:
然后在您的代码中:
Defining _cerr to nothing will fail the compilation. You could instead define a macro that you exclude while in release mode.
For example:
Then in your code:
不,绝对不。
尝试对此进行变体:(
基本上,您需要一个仅丢弃其输入的流。)
No. Absolutely, no.
Try a variation on this:
(Basically you would want a stream which just discards its input.)
对于“没有登录发布”的更好的解决方案是以下类:
使用:
A nicer solution for the "no logging in release" is the following class:
Use:
创建您自己的 NULL 流。
Create your own NULL stream.
您可以为此使用宏:
You can use a macro for this: