C++结构重新定义编译器错误

标签 c++ compiler-construction struct

我创建了一个包含以下内容的新 .h 文件:

#include "stdafx.h"
#include <string>
using namespace std;

struct udtCharVec
{
    wstring GraphemeM3;
    wstring GraphemeM2;
};

当我想编译它时,编译器告诉我“error C2011: udtCharVec: struct type redefintion”。

我进行了文本搜索,但在其他任何地方都没有定义“struct udtCharVec”。

有人看到我哪里错了吗?

最佳答案

您可能在单个翻译单元中多次包含此头文件。当第二次包含该文件时,struct udtCharVec 已经被定义,因此您会得到“类型重定义”错误。

添加 include guard .在第一次包含之后,CharVec_H 将被定义,因此文件的其余部分将被跳过:

#ifndef CharVec_H
#define CharVec_H
#include "stdafx.h"
#include <string>
using namespace std

struct udtCharVec
{
    wstring GraphemeM3;
    wstring GraphemeM2;
};
#endif

假设您的项目包含三个文件。两个头文件和一个源文件:

CharVec.h

#include "stdafx.h"
#include <string>
using namespace std

struct udtCharVec
{
    wstring GraphemeM3;
    wstring GraphemeM2;
};

字符矩阵.h

#include "CharVec.h"
struct udtCharMatrix
{
    CharVec vec[4];
};

主要.cpp

#include "CharVec.h"
#include "CharMatrix.h"

int main() {
    udtCharMatrix matrix = {};
    CharVec vec = matrix.vec[2];
};

预处理器运行后,main.cpp 看起来像这样(忽略标准库包含):

//#include "CharVec.h":
    #include "stdafx.h"
    #include <string>
    using namespace std

    struct udtCharVec //!!First definition!!
    {
        wstring GraphemeM3;
        wstring GraphemeM2;
    };
//#include "CharMatrix.h":
    //#include "CharVec.h":
        #include "stdafx.h"
        #include <string>
        using namespace std

        struct udtCharVec //!!Second definition!!
        {
            wstring GraphemeM3;
            wstring GraphemeM2;
        };
    struct udtCharMatrix
    {
        CharVec vec[4];
    };

int main() {
    udtCharMatrix matrix = {};
    CharVec vec = matrix.vec[2];
};

这个扩展文件包括两个struct udtCharVec的定义。如果您向 CharVec.h 添加 include guard,预处理器将删除第二个定义。

关于C++结构重新定义编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16757941/

相关文章:

c++ - 为结构成员分配的内存是连续的吗?如果结构成员是数组怎么办?

c - 如何使用 MPI 传递带有动态数组的自定义结构?

c++ - 将树复制到 GPU 内存

Java编译器错误谜题: "inner classes cannot have static declarations" - except for simple types

c - C程序仅在GCC中执行后才终止

c++ - 如果使用优化 (-O2, -O3),为什么这段代码的行为会有所不同?

c - 使用 malloc 和不使用 malloc 创建结构体的区别

c++ - 使用 MinGW 和 wclang 交叉编译 DLL 时,我真的需要 __declspec(dllexport) 吗?

c++ - 如何在 C++ 中将 int 连接到 wchar_t*?

c++ - 在 OpenCV 中使用 ROI?