views:

162

answers:

2

I have issue that is reproduced on g++. VC++ doesn't meet any problems. So I have 2 cpp files:

1.cpp:

#include <string>
#include <iostream>

extern const std::string QWERTY;

int main()
{
    std::cout << QWERTY.c_str() << std::endl;

}

2.cpp:

#include <string>
const std::string QWERTY("qwerty");

No magic, I just want place string constants into separated file. At link time ld produces an error: "undefined reference to `_QWERTY'" The first think to wrap both declarations into "extern "C"" - didn't help. Error and non c++ _QWERTY is still there.

Thanks in advance for any suggestions

+3  A: 

It looks like you are probably running into this bit of the standard:

In C, a const-qualified object at file scope without an explicit storage class specifier has external linkage. In C++, it has internal linkage.

Make this change to 2.cpp:

#include <string>
extern const std::string QWERTY("qwerty");

There is some more detail on what "linkage" means in this question - What is external linkage and internal linkage in C++.

1800 INFORMATION
A: 

I'd have to look it up but I think const global variables have internal linkage in C++, don't use const and it'll compile fine.

1.cpp

...
extern std::string QWERTY;
...

2.cpp
#include <string>
std::string QWERTY("qwerty");

Or you could declare/define it as a const string in a common header of course.

Adding a superfluous extern to the 2.cpp will get it to compile too, but I'm not sure that's standard or some g++ 'extra'

Pieter
unfortunately I must be sure value is immutable. So const is mandatory modifier.
Dewfy