1

If I have a class similar to this :

//body.h
class Body
{
   static int i;//line 1
};
int Body::i=2;/line 2

and a class like this:

//ball.h
#include <body.h>
//line 3
class Ball:public Body
{
    int f();
};

and in ball.cpp :

int Ball::f()
{
    return 1;
}

this results in multiple definition of i.

I tried putting extern in line1,line2 and defining it in line 3 and still having the same error, I also searched the web, most of the results I find talks about a variable declared solely(not in a class) while I have a static class variable.

I understood that extern is opposite to static but making i extern in line1 didn't help, also I saw many questions in SO , this talks about namespaces which I don't want, this doesn't address my issue.

As A note, there is no body.cpp, there are classes other than Ball that inherits body and there is main.cpp which will access all the children classes.

So what to do to be able to use Body::i outside body.h ?

PS

all classes are surrounded in header guards .

Community
  • 1
  • 1
niceman
  • 2,653
  • 29
  • 57
  • The confusion of include guards and redefinition errors must be one of the most impossible misunderstandings to root out. Thanks, Obama. – Kerrek SB May 30 '15 at 11:46

2 Answers2

5

Create another translation unit Body.cpp and move the definition there

int Body::i=2;

Even with header guards, as you mention to have them, the definition appears in multiple translation units, hence the multiple definition error.

In your particular case the static class member is a primitive, and can be initialized at the point of declaration alternatively:

class Body {
   static int i = 2;
};
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
2

You should not define the static member in the header. You need to make a source (.cpp) file for it:

body.h (declare statics but don't define)

class Body
{
   static int i; // only declare
};
// int Body::i=2; // do not define it here

body.cpp (define statics here)

#include "body.h"

int Body::i = 2; // now we define it
Galik
  • 47,303
  • 4
  • 80
  • 117