Unresolved reference to static data

B

Bob Altman

I'm obviously doing something dumb, but for the life of me I can't figure it
out. Why does the following unmanaged C++ code fail to link with an
unresolved reference to the static variable "x"?

class TestClass
{
private:
static int x;

public:
static int Test()
{
x = 5;
return x;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
int t = TestClass::Test();
return 0;
}
 
B

Ben Voigt [C++ MVP]

Bob said:
I'm obviously doing something dumb, but for the life of me I can't
figure it out. Why does the following unmanaged C++ code fail to
link with an unresolved reference to the static variable "x"?

Because x is declared and used, but never defined.

Add the following line anywhere after the end of the definition of
TestClass:

int TestClass::x;
class TestClass
{
private:
static int x;

public:
static int Test()
{
x = 5;
return x;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
int t = TestClass::Test();
return 0;
}
 
B

Bob Altman

Thanks Ben!!!!!!

Ben Voigt said:
Bob said:
I'm obviously doing something dumb, but for the life of me I can't
figure it out. Why does the following unmanaged C++ code fail to
link with an unresolved reference to the static variable "x"?

Because x is declared and used, but never defined.

Add the following line anywhere after the end of the definition of
TestClass:

int TestClass::x;
class TestClass
{
private:
static int x;

public:
static int Test()
{
x = 5;
return x;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
int t = TestClass::Test();
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top