views:

104

answers:

2

I want to have some data cache which contains some objects which I can update over an UpdateCache function. However, I'm getting problems with a LNK2001 followed by a LNK1120.

HeaderFile.h

#ifndef headerfile_included
#define headerfile_included
#include <vector>
struct MyObject {
    unsigned int A;
    unsigned int B;
};
class MyClass {
private:
    static std::vector<MyObject> myObjectCache;
public:
    static void UpdateCache ();
};
#endif

CodeFile.cpp

#include "HeaderFile.h"
void MyClass::UpdateCache () {
    myObjectCache.clear();
    /* Repopulate cache with new data */
}

The error message I get from the linked is

error LNK2001: unresolved external symbol ""private: static class std::vector > MyClass::myObjectCache" (?myObjectCache@MyClass@@0V?$vector@UMyObject@@V?$allocator@UMyObject@@@std@@@std@@A)".

fatal error LNK1120: 1 unresolved externals

My opinion is that it is some problem with the partitioning into the header file and the code file as I have had similar problems with improper partitioning. If it is again such a problem, it would be nice if you could post some rule on what to put into the header file and what into the code file since it's pretty confusing.

+4  A: 

You need to add this to a cpp file:

std::vector<MyObject> MyClass::myObjectCache;

The reason is that as a static exists without a class ever being instantiated it needs to exist whether an instance of the class is instantiated or not. The line above creates the instance of the static and thus it exists whether or not you ever create an instance of the class itself.

Goz
well *now* I see you updated your answer :) +1
Doug T.
thanks. works now :)
Etan
+3  A: 

Since your vector is static, essentially a global entity as far as the compiler is concerned, you need to be sure to give it a home in a compilation unit. That's why you have to do what @Goz says and do

std::vector<MyObject> MyClass::myObjectCache;
Doug T.