error LNK2005 "already defined" error

Mar 28, 2012 at 9:40pm
Hi,

I am trying to include a header file in two source files.
In spite of including a guard for the header I get a linker error in VS2008 saying the class have already been defined.

Error:

Misc_Functions.obj : error LNK2005: "class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,struct std::less<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const ,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > > Board_Pos" (?Board_Pos@@3V?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V12@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@@V12@@std@@@2@@std@@A) already defined in Morris_Main.obj


Files:

Global.h
Morris_Main.cpp
Misc_Functions.cpp

Code:

Global.h


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ifndef _Global_H_
#define _Global_H_


#include <map>
#include <string.h>
#include <iostream>
#include <vector>

using namespace std;

void init_variables(char*);

map<string, string> Board_Pos;
string board_pos_arr[];

vector<string> White_Coins;

vector<string> Black_Coins;

#endif  



can someone please help me with this?

Thanks in advance!
Mar 28, 2012 at 9:44pm
Due to the statements

1
2
3
4
5
6
map<string, string> Board_Pos;
string board_pos_arr[];

vector<string> White_Coins;

vector<string> Black_Coins;

in your header you are define these objects twice.
Mar 28, 2012 at 10:07pm
Thank you for the response,

I figured that the issue is solved by declaring the classes as extern.


Global.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#ifndef _Global_H_
#define _Global_H_


#include <map>
#include <string.h>
#include <iostream>
#include <vector>

using namespace std;

void init_variables(char*);

extern map<string, string> Board_Pos;
extern string board_pos_arr[];

extern vector<string> White_Coins;

extern vector<string> Black_Coins;

#endif  


Misc_Functions.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <Global.h>
#include <map>
#include <string.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>

using namespace std;


map<string, string> Board_Pos;
string board_pos_arr[];

vector<string> White_Coins;

vector<string> Black_Coins;
.....
.....


this solved my problem, if there is any other solutions to this, I'd still like to know.
Mar 28, 2012 at 10:12pm
If an object has external linkage it should be defined only once.
Topic archived. No new replies allowed.