Using static member variables.

Hello,

Since a number of previous "How do I solve my globals?" topics, I've gone the OOP-ish way of programming. And I've ran into my first problem.

The problem instance data is saved into a class ("Instance"). It features a series of static member variables, such as instance size. Since this will stay the same throughout the runtime, I made it static. Also, it allowed me to easily access it from other classes that need the variable.

Now, after a bit of reorganizing, my Instance class has a member structure that provides an interface to a large (linearized) matrix. This requires one of the static variables. Since it is part of the Instance class, I thought this wouldn't be a problem, but it turns out it is:

1>Instance.obj : error LNK2001: unresolved external symbol "public: static unsigned int Instance::n" (?d@Instance@@2IA)


Obvious solution? Remove the static and risk some insignificant memory waste of double parameters.

1>instance.h(37): error C2327: 'Instance::n' : is not a type name, static, or enumerator
1>instance.h(37): error C2065: 'n' : undeclared identifier


The line in question looks like this:
inline unsigned operator()(const int &i, const int &j) const { return dists[i*n+j]; }
(In the static version, I replace 'n' with 'Instance::n').

The inclusion-order is pretty simple right now: Main includes one file, which includes Instance.h. Anyone who sees where the problem is?
Apparently, the problem resides in a function of Instance() that uses the statics.

1
2
3
void Instance::read() {
// ...
sline >> n; // Extracts 'n' from a stringstream 

Replacing 'n' with 'Instance::n' doesn't seem to help. I'd have thought the class itself would be able to use it.
Can you display how you declared this variable? Is the class in which it resides a singleton?
It's simply a member variable of the Instance class:

1
2
3
4
5
class Instance
{
public:
	static nsize n; // 'nsize' is typedef'd as an unsigned int	
// ... 
It's simply a member variable of the Instance class:
I figured this much. This is silly but have you tried initializing the static variable inside the cpp?
...awkward. I did not. I figured it would happen automa(t/g)ically. I've added an initialization in the main.cpp and it seems to be working now.

Thanks!
If it was a constant you could in the header, but since it is not a constant you would need to put it in a source file. If initialization is in a header for a non const you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker. (which wasn't your problem but this is just added info)
Guess that's where my confusion came from. Never worked with non-const statics before!
Topic archived. No new replies allowed.