1

I'm currently finishing a library and wanted that my "Debug" logs functions were optional, at compiling time.

What I thought was: check if DEBUG is defined, and then, define my custom debug function.

Here is what I have done (a part)

#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

(I'm compiling for Arduino; that's why I need to separate the function in two.)

As I use lots of time, Serial.print succeded by a Serial.println, I wanted that debug(s), also accepted two "parameters".

So, inserting debug("ParamOne"); and debug("ParamOne", "ParamTwo"); would result in the defined function.

But, apparently, only the last defined debug is valid, overriding the first one.

What should I do, to keep the SAME name of the funcion, or is there any way more "correct" to do it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ivan Seidel
  • 2,394
  • 5
  • 32
  • 49

1 Answers1

6

#define macro names are unique, these are not function definitions, so your second #define is overwriting the first. you may want to do something like

#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
bizzehdee
  • 20,289
  • 11
  • 46
  • 76
  • 1
    [This](http://stackoverflow.com/questions/8886812/overload-c-macros) says that it is, in fact, possible to do macro overloads. The compiler would optimize the empty inline functions away, though. The resulting instructions would probably be identical. Additionally, inline functions add a lot of flexibility so I'd say go with that! +1! – jwueller Mar 31 '13 at 21:57
  • Nice! didnt'know the "inline" function... that can help me with others problems also... Just have one problem with this: debug("char*", int) will need a separate definition and so on... =/ – Ivan Seidel Mar 31 '13 at 21:57
  • 1
    just continue adding separate definitions for each, with it being inline, its only compiled in to the binary if its needed and is compiled in where it is used rather than being a separate function in a similar way to how a macro works. – bizzehdee Mar 31 '13 at 22:00