2011-06-01 14 views
0

我正在WinXP上開發一個GUI應用程序,但不幸std :: cerr/cout無處可去。我想添加一個簡單的調試方法,將消息附加到日誌文件。如何將簡單調試添加到使用預處理器的應用程序中定義

我一直在哈希在一起閱讀其他職位幾乎可行的解決方案。我可以在我的GUI應用程序中調用一個debug()方法。但是,在下面的示例應用程序中,我甚至都沒有找到解決方案。

使用:

  • 開發 - C++ v4.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 /巴。 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中是除了變化相同的 '酒吧' 到 '富'

使用,我在發現信息其他文章...

的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

有人能告訴我是什麼原因導致這個錯誤,也是一個好辦法,然後可以在其他文件適用於調試消息/班,即取消對線:在bar.cpp和Foo.cpp中

​​

分別在其他地方使用debug()?

感謝您的任何幫助。

+0

「*不幸std :: cerr/cout無處可去*」這是什麼意思? – ildjarn 2011-06-01 04:39:00

+0

@ildjarn - 這意味着在Windows GUI應用程序中,您沒有控制檯,除非您明確調用[AllocConsole](http://msdn.microsoft.com/zh-cn/library/ms681944(v = vs。 85)的.aspx)。 – 2011-06-01 07:01:55

+0

@BoPersson:但他的入口點是'main',而不是'WinMain'。 – ildjarn 2011-06-01 07:17:27

回答

0

您對日誌文件的定義被搞亂了。

當你的代碼進行預處理,你會得到:

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

你需要做的就是這樣的一個頭文件:

extern std::ofstream LOG_FILE; 

,並在一些CPP文件(或許你的主。CPP文件):

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

要禁用調試,你可以這樣做:

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

相較於您的其它調試定義未啓用的調試標誌。

您也可以將類初始化放入類似的#ifdef塊中,以避免在不使用文件時打開文件。

+0

謝謝你。我已經把'extern std :: ofstream LOG_FILE'語句放到了debug.h中。這是一個好方法,或者是更好的做法來創建一個單獨的頭文件? – ZettaiMuri 2011-06-01 07:27:25

+0

@ZettaiMuri:把它放在debug.h中很好,只要確保在cpp文件中初始化它即可 – GWW 2011-06-01 13:21:27

+0

感謝您的反饋。我正在main.cpp中初始化它。有沒有一種方法來實現這一點,以便我可以在運行時打開和關閉調試消息? – ZettaiMuri 2011-06-01 14:38:35

相關問題