Weirdness sharing const between files

I know technically this is a general programming question but it’s happening in PIO so I thought I’d ask here.

I’m working on a pretty complex program on the ESP32 platform - it has 9 .cpp files, 4 header files, lots of libraries, etc. etc.

The problem lies in sharing this variable which is defined in the “main module”:

const bool bInhibitHPControl = true;

And in the file “DisplayFuncs.cpp”, I have this at the top:

extern const bool bInhibitHPControl;

…and when I try to compile it, I get this:

Compiling .pio\build\esp32-s3-devkitm-1\src\DisplayFuncs.cpp.o
Linking .pio\build\esp32-s3-devkitm-1\firmware.elf
C:/Users/eric.HOME/.platformio/packages/toolchain-xtensa-esp-elf/bin/../lib/gcc/xtensa-esp-elf/13.2.0/../../../../xtensa-esp-elf/bin/ld.exe: .pio/build/esp32-s3-devkitm-1/src/DisplayFuncs.cpp.o:(.literal._Z18drawHeatPumpStatusv+0x38): undefined reference to `bInhibitHPControl'
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\esp32-s3-devkitm-1\firmware.elf] Error 1

I’ve tried variations on the above syntax like “const extern bool… const bool…”, none work.

But… if I comment out the code lines shown above and instead place

const bool bInhibitHPControl = true;

…in a header file that’s included in all the .cpp files, it works.

Everything I read online says that defining the variable in one place and using “extern varType varName;” in the other files is the right way to do this, but it doesn’t work.

Am I missing something?

You almost had it right, but you got things mixed up.

You have to declare the variable as extern in the header file:

extern const bool bInhibitHPControl;

and define it in a .cpp file (compilation unit)

const bool bInhibitHPControl = true;

Thanks, that worked!

The funny thing is, I’m doing it the other way (defining it in one file, declaring it as extern in others) with a bunch of other variables and it compiles just fine. The difference is the other variables aren’t constants.

This works if you only include your header file once.
If you include your header file in more than one .cpp file, you will get a redefinition error.

Stick to the standard and everything will be fine.

Declare global variables as extern in your header file and define them in one compilation unit (usually a “.cpp” file named same as the header file)

MyHeader.h

extern int myVar;

MyHeader.cpp

#include “MyHeader.h”
int myVar = 0;