I just tried to define a constant in a library if it is not defined somewhere else (e. g. in the including sketch). But it seems that both constants are independent of each other. Background: I want to create a library and define constants there but I also want to be able to "override" these constants from the sketch file to prevent changing the library code all the time.
I also tried it with a "global constants file" but this doesn't work neither...
That's my sketch file::
#define MYCONST 234
#include "myconstants.h"
#include <testLib.h>
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
while(!Serial)
delay(2000);
Serial.println("Serial ready");
Serial.print("MYCONST INO: ");
Serial.println(MYCONST);
c::begin();
}
void loop() {
// put your main code here, to run repeatedly:
}
That's my testLib.h file:
#ifndef testLib
#define testLib
#include <Arduino.h>
#include "myconstants.h"
class c {
public:
static void begin();
};
#endif
I want exactly the opposite. If MYCONST is defined in the sketch, this definition should be used. Otherwise the definition from the library (=myconstants.h file) should be used.
Your sketch and the testLib.cpp are two different translation units, they are compiled independently. It is impossible for a constant defined in your sketch to be visible in testLib.cpp.
Macros defined in your sketch before including the header will be visible in the header, but this is bad practice, because it is an ODR violation waiting to happen. Also, don't use macros for constants.
You have two options:
always set the value of the constant in myconstants.h, never in your sketch.
make the “constant” a (static) member variable of your class that you can set from your sketch.
Problem with this is that it is a constant I can't change because it is a const. So, without a changeable constant (at compile time) I can't change an array size (once at compile time)...