I have an implementation for printing out enum values in c++
If I put all the code in a .h file, everything works nicely. If I separate out the function implementation into .cpp files, I get a linker error.
Here is my main file
#include <iostream>
#include <vector>
#include "Day.h"
using namespace std;
int main(){
initializeDayNames();
Day a = Clubs;
cout << a;
}
Here is the .h file
#ifndef __Day__
#define __Day__
#include <iostream>
#include <vector>
#include <string>
using namespace std;
enum Day {Clubs, Hearts, Diamonds, Spades} ;
vector<string> DayNames = vector<string>();
ostream & operator<<(ostream & out, Day cs);
void initializeDayNames();
#endif
and the .cpp file
#include <iostream>
#include "Day.h"
#include<string>
#include<vector>
using namespace std;
void initializeDayNames(){
DayNames.push_back("Clubs");
DayNames.push_back("Hearts");
DayNames.push_back("Diamonds");
DayNames.push_back("Spades");
}
ostream & operator<<(ostream & out, Day cs){
out << DayNames[cs];
return out;
}
What am I doing wrong here
The specific error is
Error 1 error LNK2005: "class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > DayNames" (?DayNames@@3V?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@A) already defined in Day.obj main.obj
and
Error 2 fatal error LNK1169: one or more multiply defined symbols found