I include my ‘storage.h’ header file in several .cpp files. I thought I had done this correct but something not right…
using #ifndef , #define and #else to route the header accordingly with the definitions only occurring on the first call of the header. Otherwise the externs are used.
#define EE_ADDRESS_storedfrequency 0
extern byte lightmode;
This won’t work. The define guards are there to guard against multiple inclusion per compilation unit.
Conside the file
file1.cpp where you do
and consider that both header files do a
#include <common.h>. Now with the standard include guard
/* stuff */
lib1.h is included,
common.h is included too with the inner “stuff” being activate. Then
lib2.h is included, which causes again
common.h to be included but now it doesn’t define all its stuff again because of the include guards.
The same will repeat if you have a
file2.cpp which includes the two header fiels as well.
Meaning that if you do a global variable definition with
byte lightmode;in the inside of the include guard, you will indeed only include it once per
.cpp file, but with multiple cpp files, the definition will still be there in multiple
.cpp files, thus leading to the multiple definition error.
The right way is to only
extern byte lightmode; in the header file and then define the variable with
byte lightmode; in only one cpp file.
Yes… I get it… per compilation unit makes sense.
I was shown this technique many many years ago, and have somehow used it successfully when working with the C166 processor in the Keil IDE. I don’t know if somehow the defines were retained throughout the project build… I need to see if I can find the original docs out of interest,