C++ 为什么;已经定义了;?

C++ 为什么;已经定义了;?,c++,c-preprocessor,ifndef,C++,C Preprocessor,Ifndef,请在这里给我一个提示: class UIClass { public: UIClass::UIClass(); }; #ifndef __PLATFORM__ #define __PLATFORM__ UIClass Platform; #else extern UIClass Platform; #endif 我将此内容包括两次,并获得: LNK2005-平台已在.obj(MSVS13)中定义 正如您所猜测的,这个想法是只定义一次平台。为什么#ifndef或#def

请在这里给我一个提示:

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

#ifndef __PLATFORM__
#define __PLATFORM__
    UIClass Platform;
#else
    extern UIClass Platform;
#endif
我将此内容包括两次,并获得:

LNK2005-平台已在.obj(MSVS13)中定义

正如您所猜测的,这个想法是只定义一次平台。为什么
#ifndef
#define
失败?我应该如何解决这个问题?

#define
的翻译单元是本地的,但定义不是本地的。您需要在UIClass平台上放置
extern在标题和
UIClass平台中在实现文件中

如果您真的想在标题中包含定义,可以使用一些模板类魔术:

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;
名称空间详细信息{
//模板可防止多个定义
模板
一次一级DEFU平台{
静态UIClass平台;
};
//定义实例
模板def_once_平台def_once_平台::平台;
//强制实例化
模板def_once_平台def_once_平台::平台;
}
//获取参考
UIClass&Platform=详细信息::定义一次_平台::平台;
#define
是本地翻译单位,但定义不是。您需要在UIClass平台上放置
extern在标题和
UIClass平台中在实现文件中

如果您真的想在标题中包含定义,可以使用一些模板类魔术:

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;
名称空间详细信息{
//模板可防止多个定义
模板
一次一级DEFU平台{
静态UIClass平台;
};
//定义实例
模板def_once_平台def_once_平台::平台;
//强制实例化
模板def_once_平台def_once_平台::平台;
}
//获取参考
UIClass&Platform=详细信息::定义一次_平台::平台;

因为您有多个定义
平台的
cpp
文件,导致在多个对象文件中定义
平台。标识符
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
保留供实现(编译器、库等)使用。有关更多详细信息,请参阅。因为您有多个
cpp
文件定义了
\uuuuu平台
,导致在多个对象文件中定义
平台。标识符
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
保留供实现(编译器、库等)使用。有关更多详细信息,请参阅。感谢您的解释!谢谢你的解释!