0

The following code is generating a linker error while compiling with Visual Studio 2013.

#define MAX_CONTROLLERS 4 class JoypadController { public: JoypadController() : m_is_connected(false), m_gamepad(0), m_instance_id(-1), m_haptic(0) {} int JoypadController::processEvent(const SDL_Event& event); private: SDL_GameController *m_gamepad; SDL_Haptic *m_haptic; SDL_JoystickID m_instance_id; bool m_is_connected; static JoypadController m_controllers[MAX_CONTROLLERS]; static int GetControllerIndex(SDL_JoystickID instance); void Open(int device); void Close(); }; 

static JoypadController m_controllers[MAX_CONTROLLERS];

1>joypad.obj : error LNK2001: unresolved external symbol "private: static class JoypadController * JoypadController::m_controllers" (?m_controllers@JoypadController@@0PAV1@A)

Is this valid for the class JoypadController to use itself as a type? Am I missing something simple in my linker?

1
  • ...because you're now not currently dereferencing a pointer, but still trying to use a reference Commented Aug 8, 2014 at 2:55

1 Answer 1

3

Yes, a class can contain a static member of the same type as the class. Example:

struct S { static S s; // declaration }; S S::s {}; // definition int main() {} 

A member shall not be defined to have an incomplete type, and within the definition of a class, that class itself is incomplete. This is why you can't have a non-static member of the same type as the class itself. However, declaring a static member of a class does not define that static member. Declare it within the class definition, then define it further down.

If you use the static member without defining it, you will get a link error. This has nothing to do with the fact that the static member has the same type as the class. Whenever you try to use an object that hasn't been defined, you will get a link error.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't quite understand all the code. Could you help me in more detail with the class posted? I don't understand where m_controllers should be defined, or how I should define it. It looks like it's supposed to hold data like an array, but it makes calls to variables defined by the class. In the code here are the uses: if (m_controllers[i].m_is_connected) JoypadController& jc = m_controllers[event.cdevice.which]; jc.Open(event.cdevice.which);
@Impossibear Define it after the definition of JoypadController, like this: JoypadController JoypadController::m_controllers[MAX_CONTROLLERS]; optionally with an initializer.
Thank you so much. I need to study up more. This gives me a valid example to learn from now though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.