2013-05-26 42 views
1

我已经创建了以下内容的新的.h文件:当我想编译C++结构重新定义编译器错误

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

struct udtCharVec 
{ 
    wstring GraphemeM3; 
    wstring GraphemeM2; 
}; 

,编译器告诉我:“错误C2011:udtCharVec:结构类型redefintion”。

我做了一个文本搜索,并没有在其他地方定义的“struct udtCharVec”。

有人看到我出错了吗?

+0

你在你定义struct的当前文件中有错误?或者你是否使用此代码作为其他文件的包含文件? – Dineshkumar

+1

除了你的问题,不要在头文件中使用“using directive”:http://stackoverflow.com/questions/4872373/why-is-including-using-namespace-into-a-header-file- a-bad-idea-in-c –

+0

其中是头文件的使用代码?编辑您的问题并发布... – pinkpanther

回答

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]; 
}; 

预处理器已经运行后,主。 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,则第二个定义将被预处理器删除。

+0

谢谢。它的工作,但我不明白为什么。“你在一个翻译单元中多次包含这个头文件”是什么意思? – user2421725

+0

@ user2421725表示您在程序中多次包含#include ,导致CharVec_H试图定义两次,因此错误 – pinkpanther

+1

从头中删除'using namespace std'将是明智的做法。 – juanchopanza

0

通常情况下,类似的问题在“输出”窗格中有附加信息(而错误列表仅获取第一行),您可以单击以转到上一个定义。

如果它到了相同的位置,那么的确可以将该文件包含多次 - 您可以打开C++/advanced下的显示包含选项以查看列出的所有包含。

大多数.h文件应包含一次包含警戒或#pragma以避免此类错误。

此外,您不应该在头文件中包含“stdafx.h” - 这应该在.cpp文件的开始处(次优)或在项目中指定为强制包含。