问题
I am currently porting some code from Visual Studio to Mingw GCC. It seems there is a problem when I attempt to use a static variable . This code works fine in Visual studio so I am not sure what the problem might be here. I have pasted an outline of what the code looks like. If this is insufficient I could put in more.
Header file: .h
namespace LG_Wrapper
{
template <LG_Thread Thread>
class EffectApplication : public ktApplication
{
public:
static EffectApplication<Thread>& GetInstance();
protected:
.....
.....
static boost::recursive_mutex mResource;
}
}
DECLARE_LEGACY_TYPES(EffectApplication);
Source File: .cpp
namespace LG_Wrapper
{
template<>
boost::recursive_mutex EffectApplication<LG_Thread_NAME>::mResource; //LG_Thread_NAME type discussed below
template <LG_Thread Thread>
EffectApplication<Thread>& EffectApplication<Thread>::GetInstance()
{
boost::recursive_mutex::scoped_lock mutex( mResource ); //Error with mResource
static EffectApplication<Thread> instance;
return instance;
}
....
}
Now I am not sure about the LG_Thread_NAME
type.
After going through the code I noticed that I define the following in the project settings
LG_THREAD_NAME=GAME
This definition comes into play with this macro somewhere else in the code
#define DECLARE_LEGACY_TYPES(...)
I am having issue accessing mResource
The code builds fine if I comment out the statement
boost::recursive_mutex::scoped_lock mutex( mResource );
Any suggestions on why I might be getting the following error with the above code ?
(.text$_ZN10KT_Wrapper17EffectApplicationILNS_9LT_ThreadE0EE11GetInstanceEv[_ZN10LT_Wrapper17EffectApplicationILNS_9LT_ThreadE0EE11GetInstanceEv]+0x11): undefined reference to `LT_Wrapper::EffectApplication<(LT_Wrapper::LT_Thread)0>::mResource'
Update: I am certain that there is something wrong with the variable mResource because in the static method. If I do this it builds fine
boost::recursive_mutex l;
boost::recursive_mutex::scoped_lock mutex( l );
Duplicate Question Issue: I am not sure how this question is a duplicate of the links provided. In all the links provided the ops have not initialized their static variables. Here I have initialized my static variable outside the class.
回答1:
The initialization
template<>
boost::recursive_mutex EffectApplication<LG_Thread_NAME>::mResource;
still is not correct, since you initialize mResource
not for all template parameter, but only for specialization with LG_Thread_NAME
. So I guess when you try to access it with some another template parameter you've got an error.
Correct way is like this
template<LG_Thread Thread>
boost::recursive_mutex EffectApplication<Thread>::mResource;
Also I'm not sure with my answer because the error says that the problem is with LT_Wrapper
class and template parameter (LT_Wrapper::LT_Thread)0
looks strange to me.
来源:https://stackoverflow.com/questions/29662190/undefined-reference-with-a-static-instance