#define c-preprocessor constants ... what did I wrong?

120 views Asked by At

I am trying once more with arduino and create a small module just to gain fluency in the cpp sintaxe.

I am trying to create a utility module with a static method and using a header constant to decide if I have to print the debug messages or not.

But even using #ifndef to avoid duplications, I did not work

In the module DataMattersUtil I set the header constant DATA_MATTERS_DEBUG to false using #ifndef to avoid duplication. But when I execute this code, the message does not print on serial monitor because the constant is always false, even setting it to true on the module DataMattersRunner.ino that is the first to execute.

File: DataMattersRunner.ino

#define DATA_MATTERS_DEBUG true

#include <DataMattersRunner.h>

DataMattersRunner runner;

void setup() {
  runner.setup();
}

void loop() { }

File: DataMattersRunner.cpp

#include <DataMattersUtil.h>

void DataMattersRunner::setup() {
  DataMattersUtil::debug("Running ...");
}

File: DataMattersRunner.cpp

#include <DataMattersUtil.h>

void DataMattersRunner::setup() {
  DataMattersUtil::debug("Running ...");
}

File: DataMattersUtil.h

#ifndef DATA_MATTERS_DEBUG
#define DATA_MATTERS_DEBUG false
#endif

#ifndef DataMattersUtil_h
#define DataMattersUtil_h

class DataMattersUtil {
  public:
    static void debug(String message);
};

void DataMattersUtil::debug(String message) {
  if(DATA_MATTERS_DEBUG) {
    Serial.println(message);
  }
}
#endif
2

There are 2 answers

0
Stephen Newell On

Your problem is that each cpp file is handled in a different compilation unit, and you've only defined DATA_MATTERS_DEBUG to true in DataMattersRunner.ino. Because your other files are in separate compilation units, they don't see the definition in DataMattersRunner.ino.

The best solution for you is probably to provide DATA_MATTERS_DEBUG using a compiler option. I don't have Arduino experience, but with gcc you can do something like this:

g++ -c DataMattersRunner.cpp -DDATA_MATTERS_DEBUG=true
0
t.niese On

As DataMattersUtil.h is included in multiple compilation units you have to define DATA_MATTERS_DEBUG in all of them.

Instead of adding #define DATA_MATTERS_DEBUG before all #include <DataMattersUtil.h> you would use a compiler flag to do so. For gcc and clang it would be -DDATA_MATTERS_DEBUG