c++staticlinker-errorslnk2005

Linker errors for multiple defined symbols when defining a static class field


I have a class in which I defined a static integer that I hope will keep track of how many objects of that class get instantiated.

class mob {

public:

mob::mob();
mob::mob(std::string, std::string, int, int, int, int, int);
//some other stuff

private:
//some other stuff
static int mob_count;

};
int mob::mob_count = 0; 

then I define the following constructor:

    mob::mob(string name, string wName, int lowR, int highR, int health, int defense, int reward)
{
    nName = name;
    nWeapon.wName = wName;
    nWeapon.wRange.Rlow = lowR;
    nWeapon.wRange.RHigh = highR;
    nHealth = health;
    nArmor = defense;
    xpReward = reward;
    ++mob_count;
}

So what am I missing? I think i'm doing everything my text book tells me.

I get this when compiling

I hope someone can point my mistakes, thank you very much.

EDIT: @linuxuser27 helped me solve my problem, so basically i just moved the

 int mob::mob_count = 0; 

from the class definition, to the class implementation, like so:

mob.h:

class mob {

public:

mob::mob();
mob::mob(std::string, std::string, int, int, int, int, int);
//some other stuff

private:
//some other stuff
static int mob_count;

};

mob.cpp

int mob::mob_count = 0; 

constructor stays the same.


Solution

  • I assume you are declaring your class in a header file (e.g. mob.hpp) and then including the header file in multiple compilation units (i.e. cpp files). Basically this:

    main.cpp

    #include "mob.hpp" ...

    mob.cpp

    #include "mob.hpp" ...

    Remove int mob::mob_count = 0; from the header file and put it in the mob.cpp.