如何使用预处理器定义向应用程序添加简单调试

How to add simple debug to Application using preprocessor defines

本文关键字:应用程序 添加 简单 调试 定义 何使用 预处理 处理器      更新时间:2023-10-16

我正在WinXP上开发一个GUI应用程序,但不幸的是std::cerr/cout没有成功。我想添加一个简单的调试方法,将消息附加到日志文件中。

我一直在阅读其他帖子,想出一个几乎可行的解决方案。我能够在我的GUI应用程序中调用一个debug()方法。然而,在下面我试图用来寻找解决方案的示例应用程序中,甚至不要走那么远。

使用:

  • Dev-C++版本4.9.9.2
  • WinXP

以下是我的示例应用程序的结构:

C:.
|   Makefile.win
|   Project1.dev
|
---src
    |   bar.cpp
    |   bar.h
    |   foo.cpp
    |   foo.h
    |   main.cpp
    |
    +---inc
    |       debug.h
    |
    ---log

src/bar.h:

#ifndef BAR_H
#define BAR_H
class Bar
{
public:
    Bar();  
};
#endif

src/bar.cpp:

#include "bar.h"
Bar::Bar()
{
//    debug("I am Bar.");
}

src/foo.h和src/foo.cpp相同,只是将"Bar"更改为"foo"

使用我在其他文章中找到的信息。。。

src/inc/debug.h:

#ifndef MY_DEBUG_H
#define MY_DEBUG_H
#include <iostream>
#include <fstream>
#include <string>
#ifndef LOGFILE
#define LOGFILE std::ofstream logfile("log/debug.txt", std::ios::app);
#endif
#ifndef debug
#define debug(s) LOGFILE << "[" << __DATE__ << " " << __TIME__ 
            << "] " << __FILE__ << ":" << __LINE__ << " " << s << std::endl
#endif
#endif

src/main.cpp:

#include "inc/debug.h"
#include "foo.h"
#include "bar.h"
#include <iostream>
int main (int argc, char **argv)
{
    debug("Starting program."); 
    Foo *f = new Foo();
    Bar *b = new Bar();
}

当我试图编译它时,我在main.cpp的debug("Starting program.");行得到一个错误,说expected primary-expression before '<<' token

有人能告诉我是什么导致了这个错误吗?还有一个很好的方法可以在其他文件/类中应用调试消息,即取消注释行:

//    debug("I am Bar.");
//    debug("I am Foo.");

分别在bar.cpp和foo.cpp中,并在其他地方使用debug()?

谢谢你的帮助。

您对日志文件的定义搞砸了。

当你的代码被预处理时,你会得到:

std::ofstream logfile("log/debug.txt", std::ios::app); << "[" << __DATE__ << " " << __TIME__ 
        << "] " << __FILE__ << ":" << __LINE__ << " " << "Starting Program" << std::endl;

你需要在头文件中做这样的事情:

extern std::ofstream LOG_FILE;

在一些cpp文件(可能是您的main.cpp文件)中:

#include "debug.h"
std::ofstream LOG_FILE("log/debug.txt",std::ios::app);

要禁用调试,您可以执行以下操作:

#define debug(ignore)((void) 0)

与其他调试定义相比,当您的调试标志未启用时。

您也可以将类初始化放在类似的#ifdef块中,以避免在不使用文件时打开该文件。

Tbh您几乎可以将cout/cerr输出替换为直接指向文件。例如,请参阅http://www.cplusplus.com/reference/iostream/ios/rdbuf/例如。然后像往常一样使用cout/cerr。你可能需要小心冲洗等,至少如果你想实时阅读的话。