2012-09-29 48 views
1

我正在使用g ++編譯器,我想根據我的配置,將我的C++代碼的某些行註釋掉或未註釋。調試註釋和C/C++宏

我意識到,我可以這樣做:

#ifdef DEBUG 
cout << "foo" << endl; 
#endif 

但我寧願這一切是在一行:

#define DEBUG // 
DEBUG cout << "foo" << endl; 

...與DEBUG是爲//宏。但寫作#define DEBUG //什麼也沒有。任何人都可以告訴我該怎麼辦?

回答

2

但我寧願這一切是在一行:
#define DEBUG //

人們已經給出瞭如何完成你想要的好例子,但沒有人談到爲什麼你的方法沒沒有工作。

你的方法將永遠不會工作。它不能工作。沒有定義成爲評論序列開始的宏的機制,原因很簡單,因爲在預定義符號被定義的時候評論不存在。他們已經被剝奪了。

0

這在C中不是慣用的。首選使用常用的形式,例如

#ifdef DEBUG 
    count << "foo" << endl; 
#endif 

或(如assert):

#ifndef NDEBUG 
    count << "foo" << endl; 
#endif 

出於可讀性的緣故。您也可以在宏封裝此代碼:

#ifdef DEBUG 
#define PRINT_DEBUG(s) cout << s << endl 
#else 
#define PRINT_DEBUG(s) (void)0 
#endif 
4

下面是做這件事的一種方法:

#if _DEBUG 
// dbgInC defined as "printf" or other custom debug function 
#define dbgInC printf 
// dbgInCpp defined as "cout" or other custom debug class 
#define dbgInCpp cout 
#else 
// dbgInC defined as null [1] 
#define dbgInC 
// dbgInCpp defined as "if(0) cerr" or "if(1); else cerr" 
#define dbgInCpp if(0) cerr 
#endif 

這樣做的:

#ifdef DEBUG 
#define DEBUG_LOG(x) std::cout << x << std::endl; 
#else 
#define DEBUG_LOG(x) 
#endif 

DEBUG_LOG("foo") 
+0

你也可以在這個方法中使用'DEBUG_LOG(「variable =」<< variable);''這樣你就可以在cout – PSIAlt

2

One從布斯博士article絕招允許多行報表的優點:

dbgInCpp << "Debug in C++: " 
<< a // a is an integer 
<< b /* b is char array */ 
<< c // c is a float 
<< endl; 
+0

+1中使用所有可笑的黑客... – md5

+0

+1。你確實設法在一行中完成它,並且它適用於g ++。 (缺乏可移植性使我無法在當前項目中使用它。) – JellicleCat

0

你可能有

#ifndef NDEBUG 
#define DBGOUT(Out) cout << __FILE__ << ":" << __LINE__ << ":" \ 
    << Out << endl 
#else 
#define DBGOUT(Out) do {} while(0) 
#endif 

,並在你的代碼的東西使用像

DBGOUT("x is " << x); 

我使用NDEBUG symol,因爲<assert.h><cassert>使用它。