Search code examples
c++visual-studio-2010visual-studio-debugging

Class not working with static variable in c++


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 ==========


Solution

  • 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.