Pre-compile constants?

Does Sketch support pre-compile constants and pre-compile conditional blocks?

I'd like to have a bunch of debugging code that only gets compiled if some variable is defined. In C# I would have used:

#define DEBUG

#if DEBUG
    // Do logging
#

Of course.

You could have tried it in the time it took to ask.

No, I didn't know if it was a pre-compile or not. I suppose I could have compared the size of the compiled package with/without #define-#if.

The sketch is compiled as C++ after some minimal pre-processing, so C++ concepts will apply to Arduino sketches as well.

Example:


//***************************************************************
#define DEBUG       //If you comment this line the DPRINT & DPRINTLN
//lines are defined as blank.
//examples:
//DPRINTLN("Testing123");    
//DPRINTLN(0xC0FFEEul,DEC);
//DPRINTLN(12648430ul,HEX);

#ifdef DEBUG
#define DPRINT(...)    Serial.print(__VA_ARGS__)
//OR, #define DPRINT(args...)    Serial.print(args)
#define DPRINTLN(...)  Serial.println(__VA_ARGS__)
#define DRINTF(...)    Serial.print(F(__VA_ARGS__))
#define DPRINTLNF(...) Serial.println(F(__VA_ARGS__))

#else
#define DPRINT(...)     //blank line
#define DPRINTLN(...)   //blank line
#define DPRINTF(...)    //blank line
#define DPRINTLNF(...)  //blank line

#endif
//***************************************************************

2 Likes

I prefer something like this so you can use #if DEBUG rather than #ifdef DEBUG:

#define DEBUG 1

#if DEBUG
// ...
#endif
1 Like

Why ?

I can think of at least two reasons.

One (a superficial reason, perhaps) is that it's shorter to write #if DEBUG than #ifdef DEBUG.

Another is that you can write multiple conditions like #if DEBUG || WARN if you want some code to run at either "debug" or "warn" levels, for example, which can't be done as easily (if at all) with #ifdef.

2 Likes

Thank you

I prefer something like this so you can use #if DEBUG rather than #ifdef DEBUG:

#define DEBUG 1

This also allows you to do things like:

     if (DEBUG) {
        ...stuff...
     }
     if (DEBUG && packetIsV6(packet)) {
        pretteyPrint6(packet);
     }

Which will format better. And is still optimized away.
(oh - and you can easily convert it to being enabled/disabled at run-time)

2 Likes

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.