Search code examples
c++visual-c++staticmanaged-c++

How can I give a value to a static variable in a managed C++ class?


In VC++ CLR project I have a class temp. I am trying to set the static variable temp1 to 5.

I am getting a compilation error:

Error 32 error LNK2020: unresolved token (0A0005FB) "public: static int temp::temp1" (?temp1@temp@@2HA) C:\Users\user100\Documents\Visual Studio 2012\NewProject 32 bit\create min bars from data2\create min bars from data\create min bars from data5.obj

Error 33 error LNK2001: unresolved external symbol "public: static int temp::temp1" (?temp1@temp@@2HA) C:\Users\user100\Documents\Visual Studio 2012\NewProject 32 bit\create min bars from data2\create min bars from data\create min bars from data5.obj

How can I fix it?

class temp
{
    public:
    static int temp1;
};

int main(array<System::String ^> ^args)
{
    temp::temp1 = 5;
}

Solution

  • Define your static member variable:

    class temp
    {
        public:
            static int temp1;
    };
    
    int temp::temp1 = 0;
    
    // Fixed main() ;)
    int main(int argc, char** argv)
    {
            temp::temp1 = 5;
            return 0;
    }