c++ - 项目错误中的 std::map

标签 c++ gcc dictionary

我有这两个文件:

Circles.h:

#ifndef CIRCLE_H
#define CIRCLE_H
#include <map>
using namespace std;

map<int, int> colormap;

#endif

main.cpp:

#include <iostream>
#include "Circles.h"
using namespace std;

int main ()
{
     int a;
     cin>>a;
     cout<<a<<endl;
     return 0;
}

错误:

||=== Build: Debug in Mulit-game (compiler: GNU GCC Compiler) ===| obj\Debug\main.o||In function ZSt11__addressofISt4pairIKiN2sf5ColorEEEPT_RS5_':| D:\SFML Projects\Mulit-game\main.cpp|7|multiple definition ofcolormap'| obj\Debug\Circles.o:c:\program files (x86)\codeblocks\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32\bits\gthr-default.h|300|first defined here| ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

我不知道为什么会这样,因为我已经搜索了我项目的所有文件, map 只在 Circles.h 中找到。

最佳答案

我假设 map 实际上称为 colormap,并且头文件包含在多个源文件中?因为这是您获得该错误的唯一方法。

问题是您在头文件中定义变量colormap,因此它在包含头文件的每个源文件中定义。

相反,您应该只在头文件中进行外部声明,并在一个源文件中进行定义。


因此,在头文件中执行例如

extern std::map<int, int> colormap;  // Declare the colormap variable

在您的一个源文件中,在全局范围内:

std::map<int, int> colormap;  // Define the colormap variable

关于c++ - 项目错误中的 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23136142/

相关文章:

Android 词典安全问题

jquery - jQuery 对话框中的 Bing map 仅在 IE8/9 中无法正确显示

c++ - 内存中分配的SQL小表

c++ - Opencv 函数只能以 C 代码方式调用,不能以 C++ 方式调用

c++ - 控制串行端口上的各个引脚

c - 升级到Mojave后,无法在Mac上编译C程序

c++ - 调用虚函数 : compare base versus derived reference calls?

c++ - 为什么非多态 typeid 需要 RTTI?

c++ - 导入 .TLB 文件给出 "cannot open source file x.tlh"

list - 如何使用 "reduce"获取 Dart/Flutter 中对象列表中的值的总和