0

Here is my header file:

class MapObject: public ScreenObject {
    static float xoffset, yoffset;
public:
    static float Getxoffset() {
        return xoffset;
    }

};

#endif // MAPOBJECT_H

However on the line return xoffset; I get the following error: undefined reference to `MapObject::xoffset' why?

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
user2673108
  • 309
  • 1
  • 5
  • 14
  • 5
    You never defined `xoffset`, only declared it. Put this in a global scope of exactly one source file: `float MapObject::xoffset;`. – jrok Aug 23 '13 at 21:29
  • 1
    Did you define the statics `xoffset` and `yoffset` in your .cpp source file to give them proper linkage ? Remember, non-const statics have to be externally *defined* as well as declared in-class. – WhozCraig Aug 23 '13 at 21:29
  • 1
    you need to the static variables it in the .cpp file: `float MapObject::xoffset`, etc. But are you sure you want to have those static? – Dmitry Ledentsov Aug 23 '13 at 21:30
  • @WhozCraig Is everything not declared in private? – progrenhard Aug 23 '13 at 21:34
  • interesting makes sense, thanks for the info. ill remove my comment. – progrenhard Aug 23 '13 at 21:38

2 Answers2

7

Put this in a source file (by the looks of it MapObject.cpp)

#include "MapObject.h"

float MapObject::xoffset = 0;
float MapObject::yoffset = 0;


//... the rest of your MapObject code here...

In C++ non-const static members must be both declared in the class definition and defined with global scope to properly give the linker something to reference.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
  • What do you mean by "defined with external linkage" ? – Mahesh Aug 23 '13 at 21:36
  • @Mahesh See [this question](http://stackoverflow.com/questions/1358400/what-is-external-linkage-and-internal-linkage-in-c) – WhozCraig Aug 23 '13 at 21:40
  • 1
    I understand the linkage concept. I didn't understand in the context of your sentence. I think you meant the definitions should go at global scope. Isn't it ? – Mahesh Aug 23 '13 at 21:43
  • @Mahesh +1 You're correct. Thank you for the correction. Updated accordingly (been a *long* day). – WhozCraig Aug 23 '13 at 21:45
1

You have to have something like this in your MapObject.cpp:

float MapObject::xoffset = 0.0f;
float MapObject::yoffset = 0.0f;

This way you define and initialize them.

Csaba Toth
  • 10,021
  • 5
  • 75
  • 121