gpt4 book ai didi

c++ - 在 C++ 对象上使用 extern 时 undefined reference ,但不是整数类型

转载 作者:太空狗 更新时间:2023-10-29 20:28:36 25 4
gpt4 key购买 nike

尝试在 C++ 对象上使用 extern 时出现 undefined reference 错误。它似乎不会发生在整数类型上。我错过了什么?!下面的代码复制了这个问题:

文件1.cpp:

#include <string>

const std::string s("test");
int i = 99;

int main()
{
extern void Test();
Test();
}

文件2.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;
}

如果我注释掉 's' std::string 变量的用法,链接错误就会消失。

SO上还有其他类似的问题,但它们似乎都与 undefined variable 的人有关,我就是!

最佳答案

它是 std::string 上的 const,它提供了 s 内部链接。引自[3.5 程序与链接]: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

关于c++ - 在 C++ 对象上使用 extern 时 undefined reference ,但不是整数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12701130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com