I am missing something ?
Workbench, deviceOS1.2.1, Argon, local build
in .ino file (not inside any function) I define and declare
bool restartFlag = false; // used to signal a restart is needed
const int sizeOfMessageText = 60;
char tempMsg[sizeOfMessageText];
in UTILS.ccp file I define
extern bool restartFlag;
extern const int sizeOfMessageText;
extern char tempMsg[];
When I compile I get
.../src/UTILS.cpp:91: undefined reference to `sizeOfMessageText'
yet in the same UTILS.cpp I get no errors with restartFlag
The reason is that it’s a const
.
Since a const
in C++ defaults to internal linkage, you can’t just define a const
in one file and reference it as an extern
in another file. To give a const
external linkage so it can be referenced from another file, you must explicitly define it as extern
e.g.
extern const int sizeOfMessageText = 60;
Or you put your extern const
in a header file which you also include in the source file where you actually define the variable creating something like this
// --- this would be the part included from the header file ---
...
extern const int sizeOfMessageText;
...
// ------------------------------------------------------------
// --- literal code in the source file ---
...
const int SizeOfMessageText = 60;
...
achieving the same as in the former one-liner.
4 Likes
I would also suggest you to use #define instead of the extern approach, and on top of that, since it’s a constant across your code, you may want to make the variable name all caps like MSG_TXT_SIZE, it’ll help you while debugging and you can know it’s constant just by looking at it.
other option is using “static const int”
1 Like