首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

追踪与调试

2012-11-26 
跟踪与调试/*许多C程序员在跟踪代码时通常的做法是,定义一个简单的Trace类将诊断信息打印到日志文件中。程

跟踪与调试

/*
    许多C++程序员在跟踪代码时通常的做法是,定义一个简单的Trace类将诊断信息打印到日志文件中。程序员
可以在每个想要跟踪的函数中定义一个Trace对象,在函数的入口和出口Trace类可以分别写一条信息。
    缺点:增加程序开销,必须重新编译程序来打开或关闭跟踪。
    我的博客:http://blog.csdn.net/windows_nt
*/
class Trace
{
public:
 Trace(conse string &name);
 ~Trace();
 void debug(const string &msg);

 static BOOL traceIsActive;
private:
 string theFunctionName;
};

inline Trace::Trace(const string &name) : theFunctionName(name)
{
 if (traceIsActive)
 {
  cout << "Enter function " << name <<endl;
 }
}

inline Trace::debug(const string &msg)
{
 if (traceIsActive)
 {
  cout <<  msg <<endl;
 }
}

inline Trace::~Trace()
{
 if (traceIsActive)
 {
  cout << "Exit function " << theFunctionName <<endl;
 }
}

int myFunction(int x)
{
 #ifdef TRACE
 Trace t("myFunction");   //构造函数以一个函数名作为参数。
 t.debug("Some information message");
 #endif

}

//以上的代码存在性能问题,优化版:
class Trace
{
public:
 Trace(const char* name);
 ~Trace();
 void debug(const char* msg);

 static BOOL traceIsActive;
private:
 string* theFunctionName;
};

inline Trace::Trace(const char* name) : theFunctionName(NULL)
{
 if (traceIsActive)
 {
  cout << "Enter function " << *name <<endl;
  theFunctionName = new string(*name);
 }
}

inline Trace::debug(const char* msg)
{
 if (traceIsActive)
 {
  cout <<  *msg <<endl;
 }
}

inline Trace::~Trace()
{
 if (traceIsActive)
 {
  cout << "Exit function " << *theFunctionName <<endl;
  delete theFunctionName;
 }
}

int myFunction(int x)
{
#ifdef TRACE
 char* name = "myFunction";
 Trace t(name);   //构造函数以一个函数名作为参数。
#endif

}

 

热点排行