Hi All.
So, I imagine solving this issue is a matter of stringing together the proper Kabuki Dance of C++ magic words. But, it has eluded me so far. I want to declare a class with a static (shared among all class instances) array of uint8_t. All elements of the array are constant and known at compile time. I also want the compiler to compute the number of elements in the array and create a 'static const' uint8_t containing that number.
The compiler barfed on my first attempts but hinted that I needed to use 'constexpr' instead of plain-old 'const'. So, the latest (MCVE) attempt is below. Interestingly, it does compile for an Uno. But, for a Teensy 3.2 the error message is:
C:\Users\GFV\AppData\Local\Temp\arduino_build_952337\sketch/myClass.cpp:9: undefined reference to `myClass::privateArray'
I've noticed that the compiler settings for Teensy (and perhaps other ARM-based chips) enforce a stricter standard than for an Uno. Anyway, that's the message I've seen when declaring a static member in the .h but forgetting to define it in the .cpp. Not sure how it applies here.
I'd appreciate it if anyone could provide the proper incantation.
TIA.
.h file:
#ifndef MY_CLASS_H
#define MY_CLASS_H
#include <Arduino.h>
class myClass {
public:
myClass() {}
uint8_t getElement(uint8_t i);
uint8_t getNumElements();
private:
static constexpr uint8_t privateArray[] = {1, 2, 3};
static constexpr uint8_t numElements = sizeof(privateArray) / sizeof(privateArray[0]);
};
#endif
.cpp file:
#include "myClass.h"
uint8_t myClass::getNumElements() {
return numElements;
}
uint8_t myClass::getElement(uint8_t i) {
return privateArray[i];
}
.ino file:
#include "myClass.h"
myClass myObject;
void setup() {
Serial.begin(115200);
Serial.println(myObject.getNumElements());
Serial.println(myObject.getElement(0));
}
void loop() {
}