Search code examples
c++staticlinkerobject-files

unresolved external symbol in class


I have been trying for hours to get rid of my errors but it won't go away, i have looked up other posts but nothing seems to work.

I got my .H file with something like this:

using namespace std;   

     class common
    {
    public:
     common();

      static double common::s_a;
      static double common::s_b;

Then i got a .CPP file where i've defined those variables like this:

#include "common.h"

common::common()
{
  common::s_a = 100;
  common::s_b = 100;
}

Then i got this error message(actual variable name instead of a)

common.obj : error LNK2001: unresolved external symbol "public: static double common::s_playerMaxHealth" (?s_playerMaxHealth@common@@2NA)

EDIT : The problem is static, if i remove static i don't have the error anymore. However i need to use static for it to work as intented.


Solution

  • You must define these variables like so (in your .cpp file, outside of any function):

    double common::s_a;
    double common::s_b;
    

    This is a declaration (not a definition):

    class common
    {   
      static double common::s_a;
      static double common::s_b;
    

    This is a use (not a definition either):

    common::common()
    {
      common::s_a = 100;
      common::s_b = 100;
    }