2

I have created a class with a static data member. But its not getting executed even the .exe file is not being created. I am using Visual C++ express 2010.

Here is my code:

#include<iostream>
using namespace std;

class A
{
public: 
static int a;
};

int main()
{ 
    A::a = 10;
    cout << A::a;

    system("pause");
    return 0;
}

On compilation I am getting following errors:
main.obj : error LNK2020: unresolved token (0A00038B) "public: static int A::a" (?a@A@@2HA)

1>main.obj : error LNK2001: unresolved external symbol "public: static int A::a" (?a@A@@2HA)

1>C:\Users\Labeeb\documents\visual studio 2010\Projects\static variables and functions\Debug\static variables and functions.exe : fatal error LNK1120: 2 unresolved externals ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

2
  • 1
    please don't use system("pause"). It's bad practice. Commented Oct 12, 2013 at 19:52
  • Only the 50 millionth time this question has been asked. Commented Oct 12, 2013 at 20:52

1 Answer 1

2

Just add following to your source file:

int A::a;

static member variables need to be defined somewhere, outside of any function and after the declaration of the class.

Sign up to request clarification or add additional context in comments.

2 Comments

Add it outside of any functions though.
@NikBougalis I updated my answer. For me very logical, but for beginners that may be important.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.