Skip to main content
GameDev.net gamedev.net
🔒 Locked

static class object linking errors?

Started by VI2 Apr 28, 2004 at 4:43 AM 2 replies 400+ views
Original Post
VI2
VI2
Hey guys when I declare an object in my class as static I get some unresolved external errors. I have a Counter class which on creation initializes it''s counter to 0. I was hoping to create a static instance of this as a object in another class so that each time an object of this type is created, i can increment the static counter. basically the structure of the code is: class Counter { public: UINT m_Counter; Counter(){m_Counter = 0;} ~Counter(){} UINT GetCounter(){ return m_Counter } }; and i''m trying to do class BaseObject { public: static Counter myCounter; ... } why can''t i do this?
grulim
grulim
you have to DEFINE your static variable in header, and DECLARE it in cpp:

So in .h:
class BaseObject
{
public:
static Counter myCounter;
...
}

in .cpp:
Counter BaseObject::myCounter = 0;
VI2
VI2
why would i need to declare that in the cpp? All i want is one instance of my counter and the counter''s constructor is suppost to handle the initialization of the value.
ToohrVyk
ToohrVyk
Prior notice : that's "you have to DECLARE your static variable in header, and DEFINE it in cpp".

You declared it (it's declared because it is in the class definition). Great.

If you don't define it, then the linker will know that there exists an object by the name of BasicObject::myCounter. But since that object hasn't been defined anywhere, it wasn't compiled into a .obj file, so the linker will not find it anywhere and spit "unresolved external" at you until you run away.

Always remember that the compiler interprets declarations as "Tell the linker to get this once the .obj is done" and definitions as "Put this in the .obj for the linker to find it". No definition, and the linker won't find it.

On the other hand, if you define it in the header file, then any .cpp file that includes that header will also include the definition, which will then be put in the .obj of that .cpp. And you'll get "already defined in..." errors from the linker.

So your best bet is to define it somewhere where only one .cpp file can read it. That is, inside a .cpp file.

Victor Nicollet, INT13 game programmer



[edited by - ToohrVyk on April 28, 2004 2:58:20 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.