I am trying to create a class in C++ and be able to access elements of that class in more than one C++ file. I have tried over 7 possible senarios to resolve the error but have been unsuccessful. I have looked into class forward declaration which doesen’t seem to be the answer (I could be wrong).
//resources.h
class Jam{
public:
int age;
}jam;
//functions.cpp
#include "resources.h"
void printme(){
std::cout << jam.age;
}
//main.cpp
#include "resources.h"
int main(){
printme();
std::cout << jam.age;
}
Error 1 error LNK2005: "class Jam jam" (?jam@@3VJam@@A) already defined in stdafx.obj
Error 2 error LNK1169: one or more multiply defined symbols found
I understand the error is a multiple definiton because I am including resources.h in both CPP files. How can I fix this? I have tried declaring the class Jam in a CPP file and then declaring extern class Jam jam; for each CPP file that needed to access the class. I have also tried declaring pointers to the class, but I have been unsuccessful. Thank you!
The variable
jamis defined in the H file, and included in multiple CPP classes, which is a problem.Variables shouldn’t be declared in H files, in order to avoid precisely that. Leave the class definition in the H file, but define the variable in one of the CPP files (and if you need to access it globally – define it as
externin all the rest).For example: