簡體   English   中英

如何編寫一個擴展為 `#ifdef...#endif` 宏塊的 C 宏?

[英]How to write a C macro that expands to a `#ifdef… #endif` macro block?

我想在大型 C 代碼庫中插入一些調試輸出語句。 這些調試輸出語句將由編譯器選項開關控制。

調試輸出語句如下所示:

#ifdef DEBUG_FLAG
 Print(someSymbol)
#endif

為了節省一些輸入,我想知道是否可以定義一個簡單的宏來擴展到上面的調試輸出語句塊?

例如:

#define DBG_MACRO(someSymbol)  (something that can expand to above)

您不能將預處理器指令放在預處理器宏中。

但是,沒有什么可以阻止您定義一個擴展為空的宏:

#ifdef DEBUG_FLAG
#  define Print(x) Print(x)
#else
#  define Print(x)
#endif

// Expands to an empty statement if DEBUG_FLAG were not set and
// to a call to Print(something) if DEBUG_FLAG were set.
Print(something);

以上取決於Print是一個已經聲明/定義的函數。 如果宏定義為DEBUG_FLAG設置,則宏將被“替換”為自身,但 C 預處理器擴展不是遞歸的,因此擴展只發生一次,從而導致調用Print

這樣做是不可能的; 然而,有條件地定義一個宏很容易:

#ifdef DEBUG_FLAG
    #define DBG_MACRO(arg) Print(arg)
#else
    #define DBG_MACRO(arg)
#endif

最好制作一個可以處理許多調試語句的數據庫宏。 然后你可以用這 4 個字符快速包圍任何可選的調試代碼: DB( ) 這是宏:

#define DEBUG    true    // or false
#ifdef DEBUG
    #define DB(arg) { arg }
#else
    #define DB(arg)
#endif

//  Example uses:
DB(Serial.begin (9600);)

DB(if (!bLastRadarMotion)
   Serial.println("New Motion");)

DB(Serial.print("Room just became UN-Occupied after ");
Serial.print(stillSecondsThreshold);
Serial.println(" seconds.");)

DB(
Serial.print("Room just became UN-Occupied after ");
Serial.print(stillSecondsThreshold);
Serial.println(" seconds.");
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM