2

I am working on a simple top down shooter and wanted to move my ships to a separate ShipManager class, where I can manage all of them from a single location. However, upon starting this I get a linker error on my playerShip:

error LNK2001: unresolved external symbol "public: static class Ship * ShipManager::playerShip"

ShipManager.h looks like this:

class Ship;

class ShipManager
{
public:
static Ship*    playerShip;
};

I have nothing in the ShipManager .cpp yet. What am I missing? The only other place I use this code is in my game class where I am actually calling ShipManager::playerShip, and I don't get any errors there.

I include "ShipManager.h" in my game.cpp, so it should find it right? I have a feeling I'm forgetting something simple in this class.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203

2 Answers2

6

Static members have to be defined somewhere. You are declaring playerShip, but not defining it. You need to add somewhere, necessarily and only one cpp file:

Ship* ShipManager::playerShip;
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • 1
    *"preferably on a cpp file"* should be *"necessarily and only one cpp file"*, defining it in on a header file would eventually break the One Definition Rule. – Alok Save May 23 '12 at 18:20
4

You only declared the static member, you also need to define it in (only)one of your cpp files:

Ship* ShipManager::playerShip;

Good Read:
What is the difference between a definition and a declaration?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533