我有一个非常基本的类,命名为Basic,在一个更大的项目中几乎所有其他文件中都使用。在某些情况下,需要有调试输出,但在发布模式下,不应启用该输出,而应为NOOP。
目前在头部中有一个定义,它根据设置打开或关闭makro。因此,当关闭时,这绝对是NOOP。我想知道,如果我有以下代码,编译器(MSVS / gcc)是否能够优化函数调用,使其再次成为NOOP。(通过这样做,开关可以在.cpp中,并且在编译/链接时间方面,开关将会快得多)。
--Header--
void printDebug(const Basic* p);
class Basic {
Basic() {
simpleSetupCode;
// this should be a NOOP in release,
// but constructor could be inlined
printDebug(this);
}
};
--Source--
// PRINT_DEBUG defined somewhere else or here
#if PRINT_DEBUG
void printDebug(const Basic* p) {
// Lengthy debug print
}
#else
void printDebug(const Basic* p) {}
#endif发布于 2010-05-04 16:35:53
就像所有这样的问题一样,答案是-如果它对你来说真的很重要,尝试一下这种方法,并检查发出的汇编语言。
发布于 2010-05-04 17:15:24
目前,大多数优化都是在编译时完成的。一些编译器,如LLVM,能够在链接时进行优化。这是一个非常有趣的想法。我建议你去看看。
等待这些优化,你能做的如下。定义一个宏,使您可以根据是否定义了DEBUG来包含以下语句。
#ifdef DEBUG
#define IF_DEBUG (false) {} else
#else
#define IF_DEBUG
#endif你可以这样使用它
Basic() {
simpleSetupCode;
// this should be a NOOP in release,
// but constructor could be inlined
IF_DEBUG printDebug(this);
}它的可读性已经比
Basic() {
simpleSetupCode;
// this should be a NOOP in release,
// but constructor could be inlined
#if DEBUG
printDebug(this);
#endif
}请注意,您可以像使用关键字一样使用它
IF_DEBUG {
printDebug(this);
printDebug(thas);
}发布于 2010-05-04 17:48:46
#if PRINT_DEBUG
#define printDebug _real_print_debug
#else
#define printDebug(...)
#endif这样,预处理器将在调试代码到达编译器之前剥离所有调试代码。
https://stackoverflow.com/questions/2763841
复制相似问题