I would like to define array of strings in different cpp file, but there seems to be some discrepancy between definition and declaration when I try to make pointer (array element) also const. Using the same definition as declaration seems to work fine, so I suspect initialization is not an issue. In the code below I have commented out offending const - so it will compile, but if const is un-commented, linker (tested with g++ 4.6 & VS10) will not find ext_string_array.
main.cpp:
#include <iostream>
const char* cons开发者_开发技巧t 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"
};
In this context const also means static, unless you also specify extern. Change your .cpp file to this
extern const char* const ext_string_array[2] =
{
"aaa",
"bbb"
};
C++ 2003, 3.5 Program and Linkage, 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; [...]
So you need an explicit extern
in the declaration..
精彩评论