2

I have created a small program where it uses static void function to get the number and another static void function to display the number. But when ever the application runs, it gives me this error

Error 1 error LNK2001: unresolved external symbol "private: static int Thing::i" (?i@Thing@@0HA)

And here is my code

#include <iostream>
using namespace std;

class Thing{
private:
    static int i;
public:
    static void set_i(int h){
        i = h;
    }
    static void print_i(){
        cout << "The value of i is: " << i << endl;
    }
};

int main(){
    Thing::set_i(25);
    Thing::print_i();
    system("pause");
    return 0;
}
user2018675
  • 657
  • 2
  • 5
  • 15
Jim
  • 171
  • 8
  • possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Blue Ice Mar 11 '14 at 03:41
  • u must initialize the static value out side the class ..int Thing::i = 0; – vinod Mar 11 '14 at 03:50

2 Answers2

3

You should define Thing::i instead of just declaring it:

class Thing{
private:
  static int i; // this is only a declaration
  ...
}

int Thing::i = 0; // this is a definition

int main(){
  ...
}

For more details on the difference between declaration and definition, see What is the difference between a definition and a declaration?.
And here's a more static-specific question: static variable in the class declaration or definition?

Community
  • 1
  • 1
Martin J.
  • 5,028
  • 4
  • 24
  • 41
1

A static member needs to be defined outside the class.

static int i; // This is just declaration.

Add following to your code.

int Thing::i;
Nitesh
  • 2,681
  • 4
  • 27
  • 45