Link error when using static members

A

Andy

I'm trying to make a Config-class that has only one instance, as the code
below states. However, when I try to use the instance with
CConfig::GetInstance() in another .cpp-file I get a link error:

StaticTest error LNK2001: unresolved external symbol "private: static class
CConfig CConfig::m_instance" (?m_instance@CConfig@@0V1@A)

Why is this?

//Config.h
class CConfig
{
private:
static CConfig m_instance;
public:
static CConfig& GetInstance();
CConfig();
~CConfig();
};

/Config.cpp
include "StdAfx.h"
#include ".\config.h"
CConfig::CConfig()
{
}
CConfig::~CConfig()
{
}
CConfig& CConfig::GetInstance()
{
return m_instance;
}
 
A

Andy

I had a look at that example, but I'm sorry to say I didn't understand it
fully. The code later in this message works fine if I write

CConfig CConfig::m_instance = CConfig(); // 1

in any cpp-file, but not if write

CString CConfig::GetString() = "test"; // 2

As I'm starting to panic here, would you please state exactly what to with
my example below to make it work to use CConfig::GetString(); Do I really
have to use // 1 above?

class CConfig
{
private:
static CConfig m_instance;
CString m_string;
static CConfig& GetInstance();
public:
static CString GetString()
{
return m_instance.m_string;
};
CConfig();
~CConfig();
};

/Config.cpp

#include ".\config.h"
CConfig::CConfig()
{
m_string = "Test";
}
CConfig::~CConfig()
{
}

CConfig& CConfig::GetInstance()
{
return m_instance;
}
 
S

Sharad Kala

Andy said:
I had a look at that example, but I'm sorry to say I didn't understand it
fully. The code later in this message works fine if I write

ok, the mistake was that you had done in your original code was that you
just declared the static member CConfig::m_instance without defining it.
Remember static members belong to the *class* and not objects (i.e. they are
shared amongst objects of that class). You have to explicitly define it else
linker will crib (Note - There are some relaxations for static const ints
and enums, you can initialize them in the class body without explicit
definition *if* they are not used in the program)
CConfig CConfig::m_instance = CConfig(); // 1

This makes the program work becuase you are providing a definition for the
static member. This is correct.
in any cpp-file, but not if write

CString CConfig::GetString() = "test"; // 2

CConfig::GetString() = "test";
For this call to work CConfig::GetString() should return a reference.
This is completely unrelated ti your original problem. Line 1 should fix
your problem.

Sharad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top