gpt4 book ai didi

c++ - 错误 LNK1169 找到一个或多个多次定义的符号

转载 作者:行者123 更新时间:2023-11-27 23:40:19 25 4
gpt4 key购买 nike

我正在处理试图更新的遗留 C++ 代码。以前写代码的contractor很马虎,不屑于为一些类创建头文件,会把所有东西都转储到.cpp中,很多全局变量,非常大的.cpp 超过 7000 行代码的文件。现在,我正在尝试将代码分成 .h.cpp 文件。

现有代码有效(在生产环境中编译和运行)。我提取了部分实用程序代码和一些变量,并将它们移至 CASupporting.h。编译项目,在Visual Studio中出现如下错误:

LNK1169 one or more multiply defined symbols found
Error LNK2005 "int * CAValidation::__invReasonCounts" (?__invReasonCounts@CAValidation@@3PAHA) already defined in AddressValidatorLib.obj
Error LNK2005 "int * CAValidation::__invReasonCounts" (?__invReasonCounts@CAValidation@@3PAHA) already defined in AddressValidatorLib.obj

问题中的变量是

//CASupporting.h
namespace CAValidation {
...
int __invReasonCounts[7] = { 0 };
...
}

我进行了全局搜索以找出是否还有 __invReasonCounts 的任何其他定义,但结果是空的。所以,我怀疑,这与 #include "CASupporting.h" 的使用方式有关。当前包含链如下所示:CASupporting.h -> CAImpl.h -> CAImpl.cpp & CAValidator.h(2 个文件)。CAValidator.h -> CAValidator.cpp

出于好奇,我已经将 int __invReasonCounts[7] = { 0 };CASupporting.h 移到 namespace CAValidation 中“CAImpl.cpp”,其中使用了 __invReasonCounts。项目编译没有错误。

最佳答案

是的,如果您在 header 中定义了一个(非内联)全局变量,并且该 header 包含在多个 .cpp 文件中,您将因 ODR 违规而出现链接器错误。

遗留 C++ 中最常见的修复是将定义移动到 .cpp 文件中,并在 .h 文件中保留声明:

在 .h 中:

extern int __invReasonCounts[7];

在 .cpp 中:

int __invReasonCounts[7] = {0}; // compile-time initialization, safe

另外,请记住,以 __(两个下划线)开头的符号保留用于实现,不能在程序代码中使用。

关于c++ - 错误 LNK1169 找到一个或多个多次定义的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55638294/

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