std :: map中的项目错误

时间:2014-04-17 14:37:03

标签: c++ gcc map

我有这两个文件:

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:在Mulit-game中调试(编译器:GNU GCC编译器)=== |   obj \ Debug \ main.o ||在函数ZSt11__addressofISt4pairIKiN2sf5ColorEEEPT_RS5_':| D:\SFML Projects\Mulit-game\main.cpp|7|multiple definition of colormap'|中   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中找到。

3 个答案:

答案 0 :(得分:7)

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

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

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


因此,在头文件中,例如。

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

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

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

答案 1 :(得分:1)

不要在头文件中声明全局变量。

答案 2 :(得分:0)

不确定为什么你的代码不起作用。我在Visual Studio中编写它并且构建得很好。您正在使用gcc编译器,这可能更严格。我建议你不要使用&#34;使用命名空间std&#34;你的代码两次。说实话,我建议不要使用&#34;使用命名空间std&#34;一点都不而是在声明地图时,请执行以下操作:

std::map<int,int> myMap;

另外,如果您有一个全局变量(在您的情况下为colormap),最好将其声明为不在您定义类的文件中(在您的情况下为Circles?)。