我有我在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
};
当我将此文件包含在例如文件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类?
答案 0 :(得分:9)
在单个.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
限定符,因为它们似乎是常量值。
答案 1 :(得分:1)
一种解决方案是使它们都是静态的,在这种情况下,每个目标文件都有自己的副本。另一种可能性是仅将声明放在标题中并将定义放在单独的文件中。
答案 2 :(得分:0)
尝试
#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