goji
goji

Reputation: 7092

Undefined reference when using extern on a c++ object, but not integral type

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

Answers (2)

yorath
yorath

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

Jesse Good
Jesse Good

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

Related Questions