为什么"already defined"?



请在这里给我一个提示:

class UIClass
{
public:
    UIClass::UIClass();
};
#ifndef __PLATFORM__
#define __PLATFORM__
    UIClass Platform;
#else
    extern UIClass Platform;
#endif

我包括了两次并得到:

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

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

#define是翻译单元本地的,但定义不是。您需要将extern UIClass Platform;放在标头中,UIClass 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;

相关内容

最新更新