避免 c++ none 类变量中的"already defined in ..."错误/交战

Avoiding "already defined in ..." error/warring in c++ none class variables

本文关键字:in defined 错误 交战 already 避免 none 类变量 c++      更新时间:2023-10-16

我有我在实用程序命名空间中定义的全局变量。此实用程序包含在多个文件中,如下所示:

#ifndef _UT_
#define _UT_
namespace UT {
  std::string PLATFORM_LINUX_NAME = "linux";
  std::string  PLATFORM_MACOSX_NAME = "macosx";
  std::string  PLATFORM_WINDOWS_NAME = "windows";
  #if defined(OS_WIN)
    int PLATFORM = OSTYPE::PLATFORM_WINDOWS;
  #elif defined(OS_LINUX)
    int PLATFORM = PLATFORM_LINUX;
  #elif defined(OS_APPLE)
    int PLATFORM = PLATFORM_MACOSX;
  #endif
};

当我将此文件包含在例如文件 A.h 和 B.h 和 C.h 中时,我收到一个编译器警告,上面写着:

warning LNK4006: "int UT::PLATFORM" (?PLATFORM@UT@@3HA) already defined in A.obj; second definition ignored
warning LNK4006: "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > UT::PLATFORM_LINUX_NAME" (?PLATFORM_LINUX_NAME@UT@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) already defined in A.obj; second definition ignored

不涉及创建类来解决此问题的最佳方法是什么?还是创建 UT 类是唯一的方法?

在单个.cpp文件中定义变量,并在.h文件中声明它们。在UT.h

namespace UT
{
    extern const std::string PLATFORM_LINUX_NAME;
    extern const std::string PLATFORM_MACOS_NAME;
    extern const std::string PLATFORM_WINDOWS_NAME;
    extern const int PLATFORM;
}

UT.cpp

namespace UT
{
    const std::string PLATFORM_LINUX_NAME   = "linux";
    const std::string PLATFORM_MACOS_NAME   = "macosx";
    const std::string PLATFORM_WINDOWS_NAME = "windows";
    #if defined(OS_WIN)
    const int PLATFORM = OSTYPE::PLATFORM_WINDOWS;
    #elif defined(OS_LINUX)
    const int PLATFORM = PLATFORM_LINUX;
    #elif defined(OS_APPLE)
    const int PLATFORM = PLATFORM_MACOSX;
    #endif

}

我添加了const限定符,因为这些似乎是常量值。

一种解决方案是使它们全部静态,在这种情况下,每个对象文件都会获得自己的副本。另一种可能性是仅将声明放在标头中,并将定义放在单独的文件中。

尝试

#ifndef _INCL_GUARD
#define _INCL_GUARD
std::string PLATFORM_LINUX_NAME     = "linux";
std::string  PLATFORM_MACOSX_NAME   = "macosx";
std::string  PLATFORM_WINDOWS_NAME  = "windows";

#if defined(OS_WIN)
    int PLATFORM = OSTYPE::PLATFORM_WINDOWS;
#elif defined(OS_LINUX)
    int PLATFORM = PLATFORM_LINUX;
#elif defined(OS_APPLE)
    int PLATFORM = PLATFORM_MACOSX;
#endif
#endif