2014-01-06 10 views
1

은 여기 나에게 힌트를 제시하십시오 :이 두 번을 포함하고 받고 있어요"이미 정의 된"이유는 무엇입니까?

class UIClass 
{ 
public: 
    UIClass::UIClass(); 
}; 

#ifndef __PLATFORM__ 
#define __PLATFORM__ 
    UIClass Platform; 
#else 
    extern UIClass Platform; 
#endif 

:

LNK2005 - 플랫폼이 이미 .OBJ (MSVS13)에서 정의합니다.

짐작 하겠지만 아이디어는 플랫폼을 한 번만 정의하는 것이 었습니다. #ifndef 또는 #define이 실패하는 이유는 무엇입니까? 이 문제를 어떻게 해결해야합니까?

+3

여러 객체 파일에 정의되어야합니다. 식별자 '__PLATFORM__'은 구현 (컴파일러, 라이브러리 등)에서 사용하기 위해 예약되어 있습니다. 자세한 내용은 http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier를 참조하십시오. –

답변

8

#define은 번역 단위 - 로컬이지만 정의는 아닙니다. 헤더에 extern UIClass Platform;을 넣고 구현 파일에 UIClass Platform;을 넣어야합니다.

당신은 정말는 일부 템플릿 클래스 마법을 사용할 수있는 헤더의 정의를 원한다면 : 당신이 정의하는 하나의`cpp` 파일보다 더 가지고 있기 때문에`__PLATFORM__`가`Platform`의 원인이

namespace detail { 
    // a template prevents multiple definitions 
    template<bool = true> 
    class def_once_platform { 
     static UIClass Platform; 
    }; 

    // define instance 
    template<bool _> def_once_platform<_> def_once_platform<_>::Platform; 

    // force instantiation 
    template def_once_platform<> def_once_platform<>::Platform; 
} 

// get reference 
UIClass& Platform = detail::def_once_platform<>::Platform; 
+0

설명해 주셔서 감사합니다. – MixMix

관련 문제