Reputation: 7092
I'm getting undefined reference errors when trying to use extern on a c++ object. It doesn't appear to happen with integral types. What am I missing?! This code below replicates the problem:
file1.cpp:
#include <string>
const std::string s("test");
int i = 99;
int main()
{
extern void Test();
Test();
}
file2.cpp:
#include <iostream>
#include <string>
extern const std::string s;
extern int i;
void Test()
{
std::cout << s << std::endl;
std::cout << i << std::endl;
}
if i comment out the usage of the 's' std::string variable, the linking errors go away.
There are other questions on SO similar to this, but they all seem to be related to people not defining the variable, which I am!
Upvotes: 3
Views: 2139
Reputation: 199
If you remove const, it works in vc++, and if you define them both extern const, it also works.
// file1.cpp
extern const std::string s("test");
extern const int i = 99;
// file2.cpp
extern const std::string s;
extern const int i;
If you remove any 'extern' from file1.cpp, it can't compile. If the variables are defined const, you can remove 'extern' from file1.cpp.
Upvotes: 2
Reputation: 52365
It's the const
on std::string
, it gives s
internal linkage. Quote from [3.5 Program and linkage]:3:
A name having namespace scope (3.3.6) has internal linkage if it is the name of
— a variable that is explicitly declared const or constexpr and neither explicitly declared extern nor previously declared to have external linkage; or
Upvotes: 4