Multiple definition of static variable

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();
}
move line 11 to apple.cpp
won't work
What error does it give you if you move line 11 to the cpp file?

What do you do to compile?
the same error: multiple definition.
But I have actually fixed it by moving it to main.cpp
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?
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.
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.