c++ - 使用 STL 映射时出现链接器错误

标签 c++ stl linker sdl

我收到以下链接器错误:

Error 1 error LNK2001: unresolved external symbol "private: static class std::map,class std::allocator >,struct SDL_Surface *,struct std::less,class std::allocator > >,class std::allocator,class std::allocator > const ,struct SDL_Surface *> > > CSurface::loadedSurfaces" (?loadedSurfaces@CSurface@@0V?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAUSDL_Surface@@U?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAUSDL_Surface@@@std@@@2@@std@@A) CSurface.obj

CSurface编译单元的头文件和cpp文件的代码在:

IdeOne.com code post

是什么导致了这个链接器错误的发生 :( 这让我抓狂。

最佳答案

您已经声明了 loadedSurfaces 但您还没有定义它。您需要将以下内容添加到恰好一个翻译单元以实际声明变量:

map<string, SDL_Surface*> CSurface::loadedSurfaces;

现在,类定义中的 loadedSurfaces 就像是函数的原型(prototype)。当您尝试使用它时,链接器会去寻找它,因为它看到了前向声明,但它永远找不到任何地方的实际定义。您必须给它一个定义,链接器才会满意,因为它知道每个人在使用名称 loadedSurfaces 时谈论的实际翻译单元中的实际变量。

关于c++ - 使用 STL 映射时出现链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9153375/

相关文章:

类似 C++ 的 Moose 与 Perl 的 OOP 用法

c++ - 使用 map 计算词频

CMockery 模拟,重复符号错误

c++ - ld 错误的符号

c++ - 为什么在 STL 中允许未定义的行为?

c++ - 获取 LNK2001 但 Intellisense 可以找到功能

c++ - 从外部代码调用时,CMDIFrameWnd::MDIGetActive 返回 null

c++ - OpenCV (C++/Qt) - cornerSubPix 错误

java - C++ web 框架,如 spring for Java

c++ - 为什么我不能插入指向多重集的 const 指针?