Reputation: 79
I have these two files:
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;
}
Error:
||=== 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 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|first defined here| ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
I have no idea why it does this, as I've searched through all of the files of my project and the map is only found in Circles.h
.
Upvotes: 0
Views: 303
Reputation: 3153
Not sure why your code wouldn't work. I wrote it in Visual Studio and built fine. You are using gcc compiler, which might be stricter. I would advise you not to use "using namespace std" twice in your code. To be honest, I would advice not to use "using namespace std" at all. Instead when declaring a map, do the following:
std::map<int,int> myMap;
Also, if you have a global variable (in your case colormap), it is better to declare it not in a file where you define a class (in your case Circles?).
Upvotes: 0
Reputation: 409136
I'm assuming the map is actually called colormap
, and that the header file is included in multiple source files? Because that's the only way you can get that error.
The problem is that you define the variable colormap
in the header file, and so it becomes defined in each source file that includes the header.
Instead you should only make an external declaration in the header file, and do the definition in one source file.
So, in the header file do e.g.
extern std::map<int, int> colormap; // Declare the colormap variable
And in one of your source files, at the global scope:
std::map<int, int> colormap; // Define the colormap variable
Upvotes: 7