views:

235

answers:

2

I have a class called MODEL in which public static int theMaxFrames resides. The class is defined in its own header file. theMaxFrames is accessed by a class within the MODEL class and by one function, void set_up(), which is also in the MODEL class. The Render.cpp source file contains a function which calls a function in the Direct3D.cpp source file which in turn calls the set_up() function through a MODEL object. This is the only connection between these two source files and theMaxFrames.

When I try to compile my code I get the following error messages:

1>Direct3D.obj : error LNK2001: unresolved external symbol "public: static int MODEL::theMaxFrames" (?theMaxFrames@MODEL@@2HA)

1>Render.obj : error LNK2001: unresolved external symbol "public: static int MODEL::theMaxFrames" (?theMaxFrames@MODEL@@2HA)

1>C:\Users\Byron\Documents\Visual Studio 2008\Projects\xFileViewer\Debug\xFileViewer.exe : fatal error LNK1120: 1 unresolved externals

+2  A: 

It sounds very much like you have declared theMaxFrames in the class, but you haven't provided a definition for it.

If this is the case you need to provide a definition for it in a .cpp somewhere.

e.g.

int MODEL::theMaxFrames;

There's a FAQ entry for this question: static data members.

Charles Bailey
Thank you! This solved it. But I am unsure why this is necessary, could you provide some much needed insight?
LordByron
It's a language requirement. If you declare a static variable in a class, then you need to provide a definition for it outside of the class body somewhere.
Charles Bailey
Because header files do not contain variable allocations. Anything that needs to be present in the executable file needs to be declared in a CPP file somewhere. Headers are a contract between different source files to provide things. Source files are the implementations that satisfy the contracts specified in headers. If you fail to satisfy the contract, a linker error results.
Billy ONeal
@BillyONeal: It's not about variable allocations, it's about having a valid definition for a `static` data member of a class. Any declaration of a `static` data member in a class definition is always just a declaration and never a definition whether or not the class definition is in a header file or not. You need a definition of a `static` data member in some translation unit in the program. It doesn't matter which source file it's in, it could be in a header file (although this will cause problems if the header file is included in more than one translation unit in the program).
Charles Bailey
A: 

Cool man! I'm a newbie in VC++ and this post has saved my day.

I've been wrong with constant strings all this time and the static made it worst... until I read this page. Just in case it helps someone here is my today's headache solved:

// - In MyClass.h file:
static const TCHAR myToken[];

// - In my MyClass.cpp file:
const TCHAR CMyClass::myToken[] = "#BLAH#";

flyontheweb