gpt4 book ai didi

c++ - 错误: conflicting declaration of structure in multiple files

转载 作者:行者123 更新时间:2023-11-30 16:22:09 27 4
gpt4 key购买 nike

//a.cpp has following code
#include "c.h"

extern "C" {
extern const ABC abc_table[];
}

//b.h has

const ABC abc_table[] = {.....};

//c.h has
#include "b.h"
typedef struct {.....} ABC;

此代码在 Visual Studio 中编译良好

在 Linux 中它给出以下错误

a.cpp:79:79: error: conflicting declaration of ‘const ABC abc_table []’ with ‘C’ linkage
extern const ABC abc_table[];
^
In file included from c.h:4:0, from a.cpp:31:
b.h:147:1: note: previous declaration with ‘C++’ linkage
abc_table [] =

我怎样才能摆脱这个错误,为什么它在 Windows 和 Linux 中不同

最佳答案

您的程序格式不正确。

[dcl.link] (emphasis mine)

5 If two declarations declare functions with the same name and parameter-type-list to be members of the same namespace or declare objects with the same name to be members of the same namespace and the declarations give the names different language linkages, the program is ill-formed; no diagnostic is required if the declarations appear in different translation units. Except for functions with C++ linkage, a function declaration without a linkage specification shall not precede the first linkage specification for that function. A function can be declared without a linkage specification after an explicit linkage specification has been seen; the linkage explicitly specified in the earlier declaration is not affected by such a function declaration.

无论您在何处包含 a.hb.h,您都会遇到与 abc_table 声明相冲突的语言链接规范。与函数不同,变量必须显式匹配。

删除 a.h 中的链接规范,或将其添加到 b.h 中。不过,您遇到了 b.h 定义具有内部链接的对象名称的问题(由于 const),因此无法找到该符号。

我会放弃 b.h 中的声明。 header 中的对象定义应保持在最低限度,尤其是在打算与 C 代码交互时。

关于c++ - 错误: conflicting declaration of structure in multiple files,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54549274/

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