Definition of an external matrix

I would like to define an array of strings in another cpp file, but there seems to be some disagreement between the definition and the declaration when I try to make the pointer (array element) also const. Using the same definition as the declaration seems to work fine, so I suspect initialization is not a problem. In the code below, I commented on the offensive const - so it will compile, but if the const is not commented out, the linker (tested with g ++ 4.6 and VS10) will not find ext_string_array.

main.cpp:

#include <iostream> const char* const string_array[2] = { "aaa", "bbb" }; extern const char* /*const*/ ext_string_array[2]; // <- offending const int main() { std::cout << string_array[0]; std::cout << ext_string_array[0]; } 

definition.cpp:

 const char* /*const*/ ext_string_array[2] = // <- offending const { "aaa", "bbb" }; 
+4
source share
2 answers

In this context, const also means static, unless you also specify extern. Change the .cpp file to

 extern const char* const ext_string_array[2] = { "aaa", "bbb" }; 
+3
source

C ++ 2003, 3.5 Program and Communication, 3:

A name that has a namespace scope (3.3.5) has an internal relationship if that name [...]

- an object or link that is explicitly declared as const, as well as explicitly declared extern or previously declared for external reference; [...]

So you need to explicitly extern in the declaration ..

+1
source

All Articles