g++外部参考误差

发布于 2024-08-04 12:59:40 字数 496 浏览 1 评论 0原文

我有在 g++ 上重现的问题。 VC++没有遇到任何问题。 所以我有 2 个 cpp 文件:

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");

没什么魔法,我只是想将字符串常量放入单独的文件中。在链接时 ld 产生错误:“未定义对‘_QWERTY’的引用” 第一个想法将两个声明包装到“extern“C””中 - 没有帮助。错误和非 c++ _QWERTY 仍然存在。

预先感谢您的任何建议

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪荡不羁 2024-08-11 12:59:40

看来您可能遇到了这个标准:

在 C 中,文件中的 const 限定对象
没有显式存储的范围
类说明符具有外部链接。
在C++中,它具有内部链接。

对 2.cpp 进行此更改:

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

此问题中有一些有关“链接”含义的更多详细信息 - 什么是 C++ 中的外部链接和内部链接

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

一杆小烟枪 2024-08-11 12:59:40

我必须查一下,但我认为 const 全局变量在 C++ 中有内部链接,不要使用 const 并且它会编译得很好。

1.cpp

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

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

当然,您也可以将其声明/定义为公共标头中的 const 字符串。

在 2.cpp 中添加多余的 extern 也会让它编译,但我不确定这是标准的还是一些 g++ 的“额外”

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'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文