Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a class/struct/union over multiple cpp files C++

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!

like image 431
llk Avatar asked Feb 13 '26 20:02

llk


2 Answers

You're declaring the structure Jam and creating a variable called jam of this type. The linker is complaining that you've got two (or more) things called jam, because your header causes each .cpp file to declare one of its own.

To fix this, change your header declaration to:

class Jam{
public:
int age;
};

extern Jam jam;

And then place the following line in one of your .cpp sources:

Jam jam;
like image 168
Greg Hewgill Avatar answered Feb 16 '26 08:02

Greg Hewgill


You need to separate your definition from your declaration. Use:

//resources.h
class Jam{
public:
int age;
};
// Declare but don't define jam
extern Jam jam;

//resources.cpp
// Define jam here; linker will link references to this definition:
Jam jam;
like image 41
vercellop Avatar answered Feb 16 '26 08:02

vercellop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!