繁体   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