0

I have declared a static variable in a file say "example.hxx" and am calling this variable in the cxx file "example.cxx" in this way example.hxx file :-

class example{
       private:
         static int p;
       public:
         void func();
       };

CXX file

            #include <example.hxx>
             class example{
                void func(){
                    std::cout<<p;
                }
             }

I get an error of undefined reference to p. Why does this happen and how to solve this ? I have seen some answers in relation to this question but none deals with separate hxx and cxx files, instead they answer wrt main function. Would be great if someone clears my doubt !

2 Answers2

0

You have only declared p. You need to define it as well, like this, outside the class:

// .hpp file
class example{
   private:
     static int p;  // declaration
};

// .cpp file
int example::p = 42;  // definition

Alternatively, you could do:

class example{
   private:
     inline static int p = 42;  // inline definition
};
cigien
  • 57,834
  • 11
  • 73
  • 112
0

Your syntax is incorrect. First, missing ; when defining example in the .hxx file. Second, you have multiple definitions of the class example. Instead, you should define func as follows:

void example::func(){
    ....
}

Third, you have multiple definitions of func. Replace void func(){}; with void func();.

After that's done, you're also missing a definition of p. Use

class example{
private:
     static inline int p = some_value;
...

Or add a definition in the .cxx file.

Benny K
  • 868
  • 6
  • 18