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
Your problem is that each cpp file is handled in a different compilation unit, and you've only defined
DATA_MATTERS_DEBUG
totrue
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: