我创建了一个新的.h文件,其中包含以下内容:
#include "stdafx.h"
#include <string>
using namespace std;
struct udtCharVec
{
wstring GraphemeM3;
wstring GraphemeM2;
};
当我想编译它时,编译器告诉我“错误C2011:udtCharVec:struct type redefintion”。
我进行了文本搜索,并且我没有在其他地方定义“struct udtCharVec”。
有人看到我哪里出错吗?
答案 0 :(得分:4)
您可能在一个翻译单元中多次包含此头文件。当第二次包含该文件时,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;
};
CharMatrix.h
#include "CharVec.h"
struct udtCharMatrix
{
CharVec vec[4];
};
的main.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
添加包含保护,则预处理器将删除第二个定义。
答案 1 :(得分:0)
通常这样的问题在“输出”窗格中有其他信息(而错误列表只获取第一行),您只需单击转到上一个定义即可。
如果它到达同一个位置,那么确实你已经多次包含该文件 - 你可以打开C ++ / advanced下的Show include选项,看看所有包含在它们发生时列出。
大多数.h文件都应包含警戒或#pragma一次以避免此类错误。
此外,您不应在头文件中执行#include“stdafx.h” - 应在.cpp文件的开头(次优)或在项目中指定为强制包含。
答案 2 :(得分:0)
将此宏添加到头文件的顶部
#pragma once