joh*_*ohn 8 c c++ debugging visual-studio-2005
在调试模式或我正在进行测试时,我需要打印大量的各种信息,所以我使用这种方法:
#ifdef TESTING
// code with lots of debugging info
#else
// clean code only
#endif // TESTING`
Run Code Online (Sandbox Code Playgroud)
这是一个好方法,还是有其他简单而优雅的方法?
但是这样,我在两个地方重复相同的代码,如果稍后要在代码中更改,我必须在两个地方都这样做,这很费时且容易出错.
谢谢.
我正在使用MS Visual Studio.
Tuo*_*nen 17
您可以使用宏来打印调试信息,然后在发布版本中将该宏定义为空.
例如,
#ifdef _DEBUG
#define DEBUG_PRINT(x) printf(x);
#else
#define DEBUG_PRINT(x)
#endif
Run Code Online (Sandbox Code Playgroud)
使用此方法,您还可以添加更多信息
__LINE__
__FILE__
Run Code Online (Sandbox Code Playgroud)
自动调试信息.
写一次
#ifdef _DEBUG
const bool is_debig = true;
#else
const bool is_debig = false;
#endif
Run Code Online (Sandbox Code Playgroud)
然后
template<bool debug>
struct TemplateDebugHelper {
void PrintDebugInfo(const char* );
void CalcTime(...);
void OutputInfoToFile(...);
/// .....
};
// Empty inline specialization
template<>
struct TemplateDebugHelper<false> {
void PrintDebugInfo(const char* ) {} // Empty body
void CalcTime(...) {} // Empty body
void OutputInfoToFile(...) {} // Empty body
/// .....
};
typedef TemplateDebugHelper<is_debug> DebugHelper;
DebugHelper global_debug_helper;
int main()
{
global_debug_helper.PrintDebugInfo("Info"); // Works only for is_debug=true
}
Run Code Online (Sandbox Code Playgroud)