我有我在Utility命名空间中定义的全局变量.该实用程序包含在多个文件中,如下所示:
#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
};
当我将此文件包含在例如文件Ah和Bh和Ch中时,我收到的编译器警告说:
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限定符,因为它们似乎是常量值.