std::unordered_map和链接器错误

3

我有一个编译新项目的问题。

编译器输出:

1>------ Build started: Project: IRPCore, Configuration: Debug Win32 ------
1>  core.cpp
1>     Creating library D:\Repo\Inter Role Play Gamemode\sa-mp-0.2-plugin-sdk\IRP\Debug\IRPCore.lib and object D:\Repo\Inter Role Play Gamemode\sa-mp-0.2-plugin-sdk\IRP\Debug\IRPCore.exp
1>core.obj : error LNK2001: unresolved external symbol "public: static class std::tr1::unordered_map<int,struct item,class std::hash<int>,struct std::equal_to<int>,class std::allocator<struct std::pair<int const ,struct item> > > core::itemCache" (?itemCache@core@@2V?$unordered_map@HUitem@@V?$hash@H@std@@U?$equal_to@H@3@V?$allocator@U?$pair@$$CBHUitem@@@std@@@3@@tr1@std@@A)
1>main.obj : error LNK2001: unresolved external symbol "public: static class std::tr1::unordered_map<int,struct item,class std::hash<int>,struct std::equal_to<int>,class std::allocator<struct std::pair<int const ,struct item> > > core::itemCache" (?itemCache@core@@2V?$unordered_map@HUitem@@V?$hash@H@std@@U?$equal_to@H@3@V?$allocator@U?$pair@$$CBHUitem@@@std@@@3@@tr1@std@@A)
1>D:\Repo\Inter Role Play Gamemode\sa-mp-0.2-plugin-sdk\IRP\Debug\IRPCore.dll : fatal error LNK1120: 1 unresolved externals

这里是core.cpp文件

#include <iostream>
#include <unordered_map>
#include "core.h"

core::core(void)
{

}

core::~core(void)
{

}

void core::Item_Insert(int uid, item Item)
{
    core::itemCache.insert(std::make_pair<int,item>(uid, Item));

    return;
}

std::string core::convertNativeStringToString(AMX *amx, cell input)
{
    char *string = NULL;
    amx_StrParam(amx, input, string);
    return string ? string : "";
} 

我需要链接更多的库或其他内容吗?

提前感谢。

编辑:以下是从core.h中获取的核心定义。

class core
{
    public:
        static std::unordered_map<int, item> itemCache;
        core(void);
        ~core(void);
        static void Item_Insert(int uid, item Item);
        static std::string convertNativeStringToString(AMX *amx, cell input);
    private:
};
2个回答

8
如@Pete Becker所说,将此放在cpp文件的顶部:
std::unordered_map<int, item> core::itemCache;

除了

这些外,

static std::unordered_map<int, item> itemCache;

已经在.h文件中。


8
在core.cpp中添加对core::itemCache的定义。一般来说,类的静态数据成员在类定义中声明,并在源文件中定义

但他展示了他定义它的源文件,并包含一个可能声明该类的core.h。我认为他的itemcache不是静态的,他没有实例化它。但我不确定,我对这个错误很好奇。 - fonZ
@JonathanCruz:我看到一个源文件,但是我没有在任何地方看到它被定义。他包含了core.h,这可能会_声明_变量,但全局/静态变量不应该在头文件中定义。 - Mooing Duck
类和结构体项的声明在core.h中。 - Kacper
@Kacper - 是的,那就是我猜的。不过,你仍然需要在源文件中定义静态数据成员。 - Pete Becker
@JonathanCruz - 这个错误是指一个名为 core::itemCache 的静态数据成员未定义。 - Pete Becker
1
@Kacper - 再次提醒:你需要在头文件中进行声明(如core.h所示),并且必须在源文件中进行定义。这意味着需要更改core.cpp文件。 - Pete Becker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接