Click to See Complete Forum and Search --> : Link error when referencing a static member in a struct


FrozenEye
April 1st, 2008, 02:30 PM
Am trying to make a lightweight db created in runtime.
I store my data in a struct array.
Struct: struct pt_struct
{
u_char data[65];
static int count;
};
Struct array creation: pt_struct* InitPtDB(int Number)
{
return((struct pt_struct*) calloc (Number,sizeof(pt_struct)));
}
Now the InitPtDB function is in a header file called functions.h which includes the header file containing the definition of the pt_struct.

I have a dialog class buttonOnClick function with the following code: void CFrozenEyeDlg::OnBnClickedButton1()
{
int i=0;
Functions fun;
pt_struct *pts=fun.InitPtDB(150);
i=pts[0].count; //Error generated when i assigne count to i
return;
}
Error message:error LNK2001: unresolved external symbol "public: static int pkt_struct::count" (?count@pt_struct@@2HA)

The idea is to create a dynamic array of structs all with a static member count to trace the amount of pts array members initialized.
Because if i create array of pts[] with the size of 150, I may not use them all, meaning that i may have memory allocated for 150 pts elements but I only initialized 5, I need to know they are 5 and it's important to find it out using a static member in the struct definition for 2 reasons:
1.Something new i never tried and it's not working, and that motivates me ;)
2.I think thats the only way, if there is another reason i'd appretiate the sharing but I also need to know whats wrong with what am doing !

In the end, how to resolve link errors any way !?

Thanks in advance :)

wildfrog
April 1st, 2008, 02:52 PM
Somewhere in your project you need to define the static member variable:

int pt_struct::count;

- petter

Hermit
April 1st, 2008, 02:57 PM
Firstly, the linker error is generated because you have not defined the static variable. You need the following:
int pt_struct::count = 0; somewhere in your code.


Secondly, you usually access a static variable through the class and not an instance (i.e. SomeClass::staticVar, not someObject.staticVar).

Thirdly, the sort of array you're making is not good for a number of reasons, the main one being that it cannot keep track of more than one array, nothing is as automatic as it should be, and because it uses the C function calloc (in C++ you use the new/new[] operators to allocate memory). If you need a safe array in C++, std::vector (or some other STL container) is almost always the way to go.