0

I'm trying to make sure that a module only loads exactly once but when I do it my way, the compiler spits out "Undefined reference to both my static class variables :S

class Text : public Parent { private: static int Instances; static HMODULE Module; public: Text(); Text(Text&& T); Text(std::wstring T); ~Text(); virtual Text& operator = (Text&& T); }; Text::Text() : Parent() {} Text::~Text() { if (--Instances == 0) FreeLibrary(Module); // Only free the module when // no longer in use by any instances. } Text::Text(Text&& T) : Parent(std::move(T)), Module(std::move(T.Module)) Text::Text(std::wstring T) : Parent(T) // Module only loads when // this constructor is called. { if (++Instances == 1) { Module = LoadLibrary(_T("Msftedit.dll")); } } Text& Text::operator = (Text&& T) { Parent::operator = (std::move(T)); std::swap(T.Module, this->Module); return *this; } 

Any ideas why it says undefined reference to BOTH variables (Instances & Module)?

3
  • Are the definition and implementation of the class in the same file or in separate files? Where does the error message point to? Commented Mar 24, 2013 at 2:57
  • It points to the Cpp file that contains the definition for the class. The header and cpp file are separate. Gives no line numbers. Commented Mar 24, 2013 at 3:01
  • possible duplicate of Undefined reference to static variable Commented May 30, 2013 at 14:37

2 Answers 2

1

You should define your static variable in your before you can use it.

Add

int Text::Instancese = 0 // whatever value you need. 

at top of your .cpp file.

Sign up to request clarification or add additional context in comments.

4 Comments

Wow.. That worked.. Why though :S I don't understand why you'd declare a variable in the implementation file. I've never seen this before.
@CantChooseUsernames This is C++:) I think any introduction on C++ has an explanation :D google it.
@CantChooseUsernames You don’t declare it – you define it.
@KonradRudolph Thanks for the wording.
1

The class definition declares two static data members, Text::Instances and Text::Module. You also have to define those data members if the code actually uses them. Just like void f(); declares a function, but you can't call it unless you also define it. So add:

int Text::Instances; HMODULE Text::Module; 

to your source code. (This has nothing to do with whether your current code is written entirely in a header or split into header and source; if you use it you have to define it)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.