如何使用预处理器定义向应用程序添加简单调试
How to add simple debug to Application using preprocessor defines
我正在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。你可能需要小心冲洗等,至少如果你想实时阅读的话。
- 如何在控制台应用程序中添加滚动功能以显示更大的输入
- 如何向控制台应用程序添加图标
- 是否可以将 VBA 编程环境添加到我的C++应用程序?
- 将lib添加到jni应用程序中的makefile
- 添加新对话框后,MFC 应用程序启动失败并"DLL Initialization Failed"
- MFC Applicaton:如何将一组控件添加到单个文档应用程序中
- 如何在QT中添加自定义应用程序
- C 从内部程序代码上将应用程序添加到Linux程序上的启动中
- 在我的Android NDK应用程序中添加libstagefright
- 如何将boost.asio添加到windows通用应用程序项目中
- 向MFC应用程序添加许可保护
- 向iOS应用程序添加64位切片会导致崩溃
- 向Win32应用程序c++添加基本文本
- 为c++控制台应用程序添加状态栏
- 向现有的MFC应用程序添加控制台
- 将应用程序添加到启动(注册表)
- 向Android应用程序添加额外的文件
- 用户界面-向C++应用程序添加GUI的最简单方法
- 如何使用预处理器定义向应用程序添加简单调试
- 为使用Qt 5.4的iOS应用程序添加设置条目