C++上的预处理器重载

Iva*_*del 1 c++ compiler-construction debugging arduino c-preprocessor

我目前正在完成一个库,并希望我的"调试"日志功能在编译时是可选的.

我的想法是:检查是否DEBUG已定义,然后定义我的自定义debug函数.

这就是我所做的(一部分)

#if defined(DEBUG)
    #define debug(s) Serial.println(s)
    #define debug(s,t) Serial.print(s);Serial.println(t)
#else
    #define debug(s) // s
    #define debug(s,t) // s t
#endif
Run Code Online (Sandbox Code Playgroud)

(我正在为Arduino编译;这就是为什么我需要将函数分成两部分.)

由于我花了很多时间,Serial.print成功了Serial.println,我想要的debug(s),也接受了两个"参数".

因此,在插入debug("ParamOne");debug("ParamOne", "ParamTwo");将导致定义函数.

但是,显然,只有最后定义的调试有效,否则会覆盖第一个.

我应该怎么做,保持功能的相同名称,还是有任何更"正确"的做法?

biz*_*dee 6

#define宏名称是唯一的,这些不是函数定义,所以你的第二个#define会覆盖第一个.你可能想做点什么

#if defined(DEBUG)
    inline void debug(const char *s) { Serial.println(s); }
    inline void debug(const char *s, char *t) { Serial.print(s);Serial.println(t); }
#else
    inline void debug(const char *s) {  }
    inline void debug(const char *s, const char *t) { }
#endif
Run Code Online (Sandbox Code Playgroud)