为什么"已定义"?

Mix*_*Mix 1 c++ c-preprocessor ifndef

请在这里建议我一个提示:

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

#ifndef __PLATFORM__
#define __PLATFORM__
    UIClass Platform;
#else
    extern UIClass Platform;
#endif
Run Code Online (Sandbox Code Playgroud)

我包括这两次,得到:

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

你可以猜到,这个想法只是定义一次Platform.为什么#ifndef#define失败?我该怎么解决这个问题?

orl*_*rlp 8

#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;
Run Code Online (Sandbox Code Playgroud)