std :: map中的项目错误

Ilm*_*man 0 c++ gcc map

我有这两个文件:

Circles.h:

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

map<int, int> colormap;

#endif
Run Code Online (Sandbox Code Playgroud)

main.cpp:

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

int main ()
{
     int a;
     cin>>a;
     cout<<a<<endl;
     return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

|| === Build:在Mulit-game中调试(编译器:GNU GCC编译器)=== | obj\Debug\main.o ||在函数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 |首先在这里定义| || ===构建失败:2个错误,0个警告(0分钟,0秒(秒))=== |

我不知道为什么会这样做,因为我搜索了我的项目的所有文件,并且只找到了地图Circles.h.

Som*_*ude 7

我假设实际调用了地图colormap,并且头文件包含在多个源文件中?因为这是获得该错误的唯一方法.

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

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


所以,在头文件中做例如

extern std::map<int, int> colormap;  // Declare the colormap variable
Run Code Online (Sandbox Code Playgroud)

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

std::map<int, int> colormap;  // Define the colormap variable
Run Code Online (Sandbox Code Playgroud)