How to use Singleton and STL in a Win32 DLL
(WinXP SP2 and VC 7.1)
In a Win32 DLL Project:
// Kernel.h
... ...
... ...
namespace Cyber {
class __declspec( dllexport ) Kernel : public Singleton<Kernel>
{
public:
Kernel(void);
~Kernel(void);
public:
static Kernel& GetSingleton(void);
static Kernel* GetSingletonPtr(void);
private:
std::string m_strName;
... ...
... ...
}
}
// Kernel.cpp
#include "Kernel.h"
namespace Cyber {
template<> Kernel* Singleton<Kernel>::ms_Singleton = 0;
Kernel* Kernel::GetSingletonPtr(void)
{
return ms_Singleton;
}
Kernel& Kernel::GetSingleton(void)
{
assert( ms_Singleton );
return ( *ms_Singleton );
}
Kernel::Kernel(void)
{
}
Kernel::~Kernel(void)
{
}
... ...
... ...
}
Now, Compile, and Success.
In a Win32 Project:
// MyTest.h
#include "Kernel.h"
#pragma comment( lib, "Kernel.lib" )
using namespace Cyber;
... ...
... ...
// MyTest.cpp
#include "MyTest.h"
... ...
... ...
void Test()
{
Kernel *pKernel = new Kernel();
... ...
... ...
delete( pKernel );
}
... ...
... ...
Now, Compile, and Error!
The message is:
stdafx.obj : error LNK2001: unresolved external symbol "protected: static class Cyber::Kernel * Cyber::Singleton<class Cyber::Kernel>::ms_Singleton" (?ms_Singleton@?$Singleton@VKernel@Cyber@@@Cyber@@1PAVKernel@2@A)
Debug/CyberContainer.exe : fatal error LNK1120: 1 unresolved externals
Who can tell me why?
How can I resolve the problem?
Thanks very much!
[Edited by - coderwu on December 19, 2005 4:03:24 AM]
When working with static member variables you need to do something extra:
You're probably missing that last line; the definition of the variable. Unlike non-static member variables static ones are not automatically defined because there is no instance to define them in.
Illco
// Header file.class X{ // Declaration: static X* m_pInstance;};// CPP-file#include "X.h"// DefinitionX* X::m_pInstance = NULL;
You're probably missing that last line; the definition of the variable. Unlike non-static member variables static ones are not automatically defined because there is no instance to define them in.
Illco
Did you forget to __declspec(dllimport) your exported classes in the Win32 application?
Enigma
Enigma
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement