Undefined reference to an array of constants

a.cpp

const unsigned char whatever[123] = { /* ... */ }; 

hijras

 extern const unsigned char whatever[123]; 

b.cpp

 #include "ah" unsigned char x = whatever[0]; // error: undefined reference to 'whatever' 

Why does an undefined link error occur? Without const error disappears.

How can I share an array of constants among several translation units?

+8
c ++ arrays linker header const
source share
5 answers

This is one of the quirks that people face, it is just a question that you have defined the header file ah, which declares a const array of 123 characters and assigns it an external reference. When it is included in the b.cpp file, you basically promise the compiler that it will find in some other translation unit.

But each const variable has a dark secret - it falls inside its defining translation unit, because it is implicitly defined by a static connection. You promised that your compiler whatever will be divided into several units of translation, but in fact it is loyal to only one unit of translation and does not like to share. And, well, you know everything else.

Decide by explicitly specifying extern in the implementation file.

+9
source share
 3.5/3 A name having namespace scope (3.3.5) has internal linkage if it is the name of ... β€” an object or reference that is explicitly declared const and neither explicitly declared extern nor previously declared to have external linkage; ... 

Vars like

  const int x = 10; 

are defined implicitly as "static".

To make them non-static (thus not internal), use the extern modifier in the .c file.

Try using

 extern const unsigned char whatever[123] = { /* ... */ }; 
+4
source share

const has static (internal) communication by default in C ++, use extern const in your .c file. This is a random SO stream that contains more information. Or google "linkage in C ++".

+1
source share

in C ++, const is a compilation-time constant, e.g.

 const int cc = 100; int a[cc]; 

we can use const to define an array in C ++, but we cannot C. Since it is a const whose value cannot be changed, it does not need to share them between several files. So const has an internal connection.

0
source share

To fix this, a.cpp should do:

 #include "ah" 

before determining whatever .

If there is no previous declaration in the region, then const unsigned char whatever[123] = {...}; will have an internal binding. But if ah enabled, then the definition matches the previous declaration. The header defines whatever external referenced, and the definition matches the name.

As others have mentioned, you can also put extern in the definition so that this error does not occur if you forget #include "ah" . But it’s still best to include headers announcing everything we’re trying to define publicly.

0
source share

All Articles