【问题标题】:WHY "already defined"?为什么“已经定义”?
【发布时间】:2014-01-24 04:06:12
【问题描述】:

请在这里给我一个提示:

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

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

我将这两次包括在内并得到:

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

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

【问题讨论】:

  • 因为您有多个定义__PLATFORM__cpp 文件导致Platform 在多个目标文件中定义。标识符__PLATFORM__ 保留供实现(编译器、库等)使用。有关更多详细信息,请参阅stackoverflow.com/questions/228783/…

标签: c++ c-preprocessor ifndef


【解决方案1】:

#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;

【讨论】:

  • 感谢您的解释!
猜你喜欢
  • 2020-08-25
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 2012-09-13
  • 2015-06-24
  • 1970-01-01
相关资源
最近更新 更多