Jim
Jim

Reputation: 171

static void function linking error

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;
}

Upvotes: 2

Views: 234

Answers (2)

Nitesh
Nitesh

Reputation: 2830

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;

Upvotes: 1

Martin J.
Martin J.

Reputation: 5118

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?

Upvotes: 3

Related Questions