2013-05-26 3 views
1
나는 다음과 같은 내용으로 새로운 .H 파일을 만든

: 나는 그것을 컴파일 할 때C++ 구조체 재정의 컴파일러 오류

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

struct udtCharVec 
{ 
    wstring GraphemeM3; 
    wstring GraphemeM2; 
}; 

는, 컴파일러는 나에게 "udtCharVec : 구조체 유형 redefintion 오류 C2011"을 알려줍니다.

나는 텍스트 검색을했고, 나는 다른 곳 정의 "구조체 udtCharVec"가 없습니다.

어디서 잘못 본 사람이 있습니까?

+0

구조체를 정의한 현재 파일에 오류가 있습니까? 또는이 코드를 다른 파일의 포함 파일로 사용하고 있습니까? – 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

아마도이 헤더 파일을 하나의 번역 단위에 두 번 이상 포함시킬 것입니다. 파일이 두 x 째로 포함될 때 struct udtCharVec이이 L 정의 되었으 G로 "유형 재정의"오류가 발생합니다.

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

이 확장 파일 0 struct udtCharVec의 두 가지 정의를 포함한다. CharVec.h에 포함 보호를 추가하면 두 번째 정의가 전처리 기에서 제거됩니다. 그런

+0

감사합니다. 그것은 효과가 있었지만, 나는 왜 그런지 이해하지 못한다."이 헤더 파일을 단일 번역 단위에 두 번 이상 포함시킬 확률이 높음"은 무엇을 의미합니까? – user2421725

+0

@ user2421725는 프로그램에 #include 을 두 번 이상 포함 시키므로 CharVec_H가 두 번 정의되도록합니다. 따라서 오류 – pinkpanther

+1

헤더에서'using namespace std'를 제거하는 것이 좋습니다. – juanchopanza

0

일반적으로 문제는 출력 창 (오류 목록은 첫 번째 라인을 느끼는 동안)에서 추가 정보를 가지고, 당신은 이전 정의로 이동을 클릭 할 수 있습니다. 이 같은 위치에 가면

후 실제로이 파일을 여러 번 포함이 - 당신이 쇼를 켤 수는 일이 모든이 목록에 포함 참조 고급 ++/C에 따라 옵션이 포함되어 있습니다. 이한다 .H 파일의

대부분은 경비를 포함하거나 한 번 이러한 오류를 방지하기 위해의 #pragma.

또한 헤더 파일에 #include "stdafx.h"를 사용하면 안됩니다.이 파일은 .cpp 파일의 시작 부분 (준 최적화) 또는 강제 포함 파일로 프로젝트에서 지정해야합니다.