Communication error due to constant array of pointers in C ++ 03 / C ++ 11

This issue reproduces in g ++ before -std=c++14 . A binding error is generated due to const highlighting shown in the following codes. It disappears if the RHS const is removed.

 /* main.cpp */ const char* const arr[2] = {"Hello", "World"}; // ^^^^^ int main () {} 

and

 /* foo.cpp */ extern const char* const arr[2]; // ^^^^^ const char* foo () { return arr[0]; } 

When compiling: g++ [-std=c++11] main.cpp foo.cpp it gives the following binding error:

 In function `foo()': undefined reference to `arr' 

Is this a compiler error or a language restriction / function?

+5
source share
1 answer

As Quentin noted, project n4296 clearly states that in chapter 3.5 “Program and Communication” [basic.link] §3 (emphasize mine)

A name that has a namespace scope (3.3.6) has an internal relationship if that name
(3.1) - a template for a variable, function, or function that is explicitly declared static; or,
(3.2) - a variable from a non-volatile type with a constant const , which is not explicitly declared extern or previously declared to have an external connection;

When you declare arr constant, it is implicitly specified by the internal link. Committing is trivial:

 /* main.cpp */ extern const char* const arr[2] = {"Hello", "World"}; 

However, best practice would recommend having extern const char* const arr[2]; in the header included in all files, using arr to correctly share the declaration, and then add const char* const arr[2] = {"Hello", "World"}; to one of these files const char* const arr[2] = {"Hello", "World"}; effectively yielding:

 /* main.cpp */ extern const char* const arr[2]; // directly or more likely through an include... ... const char* const arr[2] = {"Hello", "World"}; 
+3
source

All Articles