gpt4 book ai didi

c++ - 为什么删除 const 会给我链接器错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:09:06 24 4
gpt4 key购买 nike

我有一个全局变量:

const std::string whiteSpaceBeforeLeadingCmntOption = "WhiteSpaceBeforeLeadingComment";

当我删除此变量声明中的 const 时,我多次出现以下链接器错误:

error LNK2005: "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > whiteSpaceBeforeLeadingCmntOption" (?whiteSpaceBeforeLeadingCmntOption@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) already defined in REGISTER_TO_UNSRLZ.obj

这是一个 .h 文件,它包含在不同的地方,但我在它上面有一个 #ifndef 带以避免在几个地方包含它。知道错误是从哪里来的吗?

最佳答案

这在 .h 中有 const 时有效,因为 const 表示静态,因此您可以在多个编译环境中使用相同的变量。

通过删除 .h 文件中定义的变量的常量,您将在同一程序中创建具有相同标识符的多个实例。

如果你需要删除 const,在 .h 中,你可以这样做:

extern std::string whiteSpaceBeforeLeadingCmntOption;

然后有:

std::string whiteSpaceBeforeLeadingCmntOption = "";

在您的一个 .cpp 文件中。

关于c++ - 为什么删除 const 会给我链接器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1094387/

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