Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ external reference error

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

like image 365
Dewfy Avatar asked Feb 15 '26 19:02

Dewfy


1 Answers

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++.

like image 132
1800 INFORMATION Avatar answered Feb 17 '26 09:02

1800 INFORMATION



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!