External reference error g ++

I have a problem that is reproducible in g ++. VC ++ meets no problem. 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;

}

      

cpp file:

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

      

No magic, I just want the lines of the line to be split into a separate file. At the time of the link, ld gives an error: "undefined reference to` _QWERTY "The first consider wrapping both declarations in" extern "C" - it did not help. The error and not C ++ _QWERTY are still there.

Thanks in advance for any suggestions

+2


source to share


2 answers


It looks like you probably came across this standard:

In C, an object with a constant in a file scope without an explicit storage class specifier has external linkage. In C ++, it has an internal linkage.

Make this 2.cpp change:



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

      

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

+6


source


I would have to watch it, but I think const globals are internally linked in C ++, don't use const

it and it will compile just 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 the general header, of course.

Adding redundancy extern

to 2.cpp will also make it compile, but I'm not sure if standard or some g ++ 'extra'

0


source







All Articles