views:

83

answers:

2

Can you help? The following code:

class MT
{
public:
    static int ms_number;

};

int MT::ms_number;

yields:

Error   8   error LNK2005: "public: static int MT::ms_number" 
      (?ms_number@MT@@2HA) already defined in ProjName.obj

Why?

+11  A: 

You need to move this line:

int MT::ms_number;

out of your .h file and into a single .cpp file.

R Samuel Klatchko
great! it works! thanks!but why? what's the problem of it to be in the .h?
Hellfrost
@Hellfrost: You're only allowed to define it once. If it's in a header, then it will end up being defined in every source file that includes the header.
Mike Seymour
A: 

The static needs to be defined as extern, in addition to R Samuel Klatchko's answer.

DeadMG
No it doesn't. That's only needed for objects at namespace scope, not static class members.
Mike Seymour