我想将一些调试输出语句插入到一个大的C代码库中.这些调试输出语句将由编译器选项开关控制.
debug输出语句如下所示:
#ifdef DEBUG_FLAG
Print(someSymbol)
#endif
Run Code Online (Sandbox Code Playgroud)
为了节省一些打字,我想知道是否可以定义一个扩展到上面的调试输出语句块的简单宏?
例如:
#define DBG_MACRO(someSymbol) (something that can expand to above)
Run Code Online (Sandbox Code Playgroud)
您不能将预处理程序指令放在预处理器宏中.
但是,没有什么可以阻止你定义一个扩展为空的宏:
#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);
Run Code Online (Sandbox Code Playgroud)
以上内容取决于Print是否已经声明/定义的函数.如果使用DEBUG_FLAGset 定义宏,则宏将被"替换"为自身,但C预处理器扩展不是递归的,因此扩展只发生一次,从而导致调用Print.
这样做是不可能的; 但是,有条件地定义宏很容易:
#ifdef DEBUG_FLAG
#define DBG_MACRO(arg) Print(arg)
#else
#define DBG_MACRO(arg)
#endif
Run Code Online (Sandbox Code Playgroud)