0

I am using static variable. After referring to Unresolved external symbol on static class members, I modified the program with Abc::ct

#include <iostream>

class Abc
{
private:
    static unsigned int ct;

public:
    void f1()
    {
        for (int i = 0; i < 5; ++i)
            f2();
    }

    void f2() {
        Abc::ct = 0;
        if (Abc::ct == 0)
            std::cout << "Zero iteration\n";

        std::cout << Abc::ct << "\t";
        ++Abc::ct;
    }
};



int main()
{
    Abc obj;
    obj.f1();
}

but getting error as error LNK2001: unresolved external symbol "private: static unsigned int Abc::ct" in MSVC or undefined reference to Abc::ct in g++. How can I define static variable in class Abc?

ewr3243
  • 397
  • 3
  • 19

2 Answers2

0

You declared your static variable, but you did not define and initialize it. Above main(), but outside of your class, add the following line:

unsigned int Abc::ct = 0;

or, if you are using C++17, you can change your:

static unsigned int ct;

to:

static inline unsigned int ct = 0;
Fureeish
  • 12,533
  • 4
  • 32
  • 62
0

You have to define it:

unsigned int Abc::ct = 0;

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302