siva
siva

Reputation: 1721

How to fix "undefined reference" compiler error

find a bug in following code :

class A
{
   public:
    static int i;
    void print()
    {
      cout<< i << endl ;
    }
 };

 int main()
 {
    A a;
    a.print();
  }

I run above code, and I am getting "undefined reference to `A::i'" . Why I am getting this error ?

Upvotes: 4

Views: 2049

Answers (2)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

Since A::i is a static member, it has to be defined outside of the class:

using namespace std;

class A
{
public:
    static int i;  // A::i is declared here.

    void print()
    {
        cout << i << endl;
    }
};

int A::i = 42;     // A::i is defined here.

Upvotes: 12

Naveen
Naveen

Reputation: 73433

The static int i in the class A is just a declaration, you need to define it outside the class by adding a statement int A::i = 0;

Upvotes: 7

Related Questions