Sign in to follow this  

How to use Singleton and STL in a Win32 DLL

This topic is 4375 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

(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]

Share this post


Link to post
Share on other sites
When working with static member variables you need to do something extra:

// Header file.
class X
{
// Declaration:
static X* m_pInstance;
};

// CPP-file
#include "X.h"

// Definition
X* 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

Share this post


Link to post
Share on other sites
Quote:
Original post by Enigma
Did you forget to __declspec(dllimport) your exported classes in the Win32 application?

Enigma


Thanks, It's my fault. Now, It's OK!

At the same time, thank Illco for your reply!

Share this post


Link to post
Share on other sites

This topic is 4375 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this