a.cpp
const unsigned char whatever[123] = { /* ... */ };
a.h
extern const unsigned char whatever[123];
b.cpp
#include "a.h"
unsigned char x = whatever[0];
// error: undefined reference to 'whatever'
Why do I get an undefined reference error? Without the const, the error goes away.
How do I share an array of constants among multiple translation units?
This is one of the quirks people run into, it’s simply a matter that you’ve defined an a.h header file which declares a const array of 123 chars, and assigned it external linkage. When it is included into the b.cpp file, you’re basically promising the compiler it’s going to find in some other translation unit.
But, every
constvariable has a dark secret – it’s trapped inside its defining translation unit because it is implicitly given static linkage. You promised your compilerwhateverwill be shared across multiple translation units, but it is actually loyal to just one translation unit and doesn’t like to be shared. And, well, you know the rest.Resolve by explicitly stating
externin the implementation file.