1. 程式人生 > >【轉】用宏定義代替printf函數

【轉】用宏定義代替printf函數

tar 版本 data eas article target else define ref

問題提出

有時候我們想用宏定義來決定是編譯debug版本的代碼還是release的代碼,dubug版本的代碼會通過printf打印調試信息,release版本的代碼則不會。我們總不能對每一條printf都這樣寫:

1 #if _DEBUG_
2 printf("hello world!");
3 #endif

這樣子實在是太麻煩了!萬一要各個地方都要打印,會使版面看起來很亂。

解決方法

我後來想到一個方法,可以使用宏定義代替printf函數,由於printf是可變參數的函數,這裏就要用到變參宏(…和__VA_ARGS__)。
在頭文件下寫此代碼

1 #define _DEBUG_ 1
2
3 #if _DEBUG_ 4 #define PR(...) printf(__VA_ARGS__) 5 #else 6 #define PR(...) 7 #endif

後面需要打印調試信息的時候使用PR宏就可以了,如果需要release版本,不打印調試信息,就把DEBUG設置為0,編譯出來的程序就不會打印調試信息了。

示例代碼清單

開發環境VS2013。當DEBUG設置為1,打印PR的信息;當DEBUG設置為0,不打印PR的信息。

 1 #include "stdafx.h"
 2 
 3 #define _DEBUG_ 1
 4 
 5 #if _DEBUG_
 6 #define
PR(...) printf(__VA_ARGS__) 7 #else 8 #define PR(...) 9 #endif 10 11 int _tmain(int argc, _TCHAR* argv[]) 12 { 13 14 printf("debug test!\r\n"); 15 16 PR("hello world!\r\n"); 17 PR("string:%s\r\n", "data"); 18 PR("integer:%d\r\n", 100); 19 20 return 0; 21 }

提醒

該技巧可以用在單片機C語言開發上,切換版本非常方便。
keil環境下如何重定向printf到串口,可以參考這裏。

來源

【轉】用宏定義代替printf函數