Multiple definition of static variable

Jan 10, 2014 at 12:35pm
How can I use static variable? Everytime I compile I get an error: multiple definition.

If I use one file for everything it works. But when I seperate it into .h and .cpp file i get this error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//apple.h file

class Apple{
public:
	Apple();
	static int weight;
	void cut();

};

int Apple::weight;

//apple.cpp file
#include <iostream>
#include "apple.h"
using namespace std;

Apple::Apple()
{

}

void Apple::cut()
{
    cout << Apple::weight << endl;
}

//main.cpp
#include <iostream>
#include "apple.h"
using namespace std;

int main()
{
    Apple app;
    app.cut();
}
Jan 10, 2014 at 1:03pm
move line 11 to apple.cpp
Jan 10, 2014 at 1:42pm
won't work
Jan 10, 2014 at 2:06pm
What error does it give you if you move line 11 to the cpp file?

What do you do to compile?
Jan 10, 2014 at 4:17pm
the same error: multiple definition.
But I have actually fixed it by moving it to main.cpp
Jan 10, 2014 at 4:36pm
It shouldn't matter what cpp file its in, as long as it's only in 1 cpp file.

You aren't #including cpp files in other cpp files, are you?
Jan 10, 2014 at 7:16pm
Nope. You can see all in includes in my code above. I think the reason of that error is "apple.h" is included twice, once in apple.cpp and once in main.cpp. That's why it is redefined I guess.
Jan 10, 2014 at 7:26pm
Yes.... having it in apple.h would have the redefined error for the reason you describe. That is correct.

However having it in apple.cpp should work just fine.
Topic archived. No new replies allowed.