我收到了多次声明静态数据成员的链接错误。我采取了所有必要的预防措施,以避免多次包含头文件,但我仍然收到错误。
//dummymessage.h
#ifndef DUMMY_MESSAGE
#define DUMMY_MESSAGE
#pragma once
#include "stdafx.h"
#include "string"
class CDummyMessage
{
private:
static int CDummyMessage::ObjCount1;
public:
CDummyMessage(void);
CDummyMessage(std::string content, int type);
~CDummyMessage(void);
private:
std::string m_Message_content;
int m_type;
};
int CDummyMessage::ObjCount1 = 0;
#endif
// dummymessage.cpp
#include "stdafx.h"
#include "iostream"
#include "DummyMessage.h"
using namespace dummy;
CDummyMessage::CDummyMessage(void)
{
std::cout<<"Constructor called. ID: "<<++CDummyMessage::ObjCount1<<std::endl;
}
CDummyMessage::~CDummyMessage(void)
{
std::cout<<"Destructor called. ID: "<<--CDummyMessage::ObjCount1<<std::endl;
}
CDummyMessage::CDummyMessage(std::string content, int type):
m_Message_content(content)
{
}
// main.cpp中
#include "stdafx.h"
#include "windows.h"
#include "list"
#include "process.h"
#include "iostream"
#include "DummyMessage.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
for(auto i = 0;++i < 10000;){
CDummyMessage* l_pNewMsg = new CDummyMessage("Test message", i);
g_Message_queue.push_front(l_pNewMsg);
} return 0;
}
我收到链接错误: -
Error 1 error LNK2005: "private: static int dummy::CDummyMessage::ObjCount1" (?ObjCount1@CDummyMessage@dummy@@0HA) already defined in DummyMessage.obj C:\Users\Veil\documents\visual studio 2012\Projects\SmartPointerExample\SmartPointerExample\SmartPointerExample.obj
答案 0 :(得分:1)
将您的CDummyMessage::ObjCount1
定义移至源文件。
标题保护只保护您的标题不会被包含在同一个翻译单元中多次;它们不会阻止它们被不同的翻译单元包括在内。
目前,包含dummymessage.h
标头的每个翻译单元都在定义CDummyMessage::ObjCount1
。当编译器尝试将所有代码链接在一起时,它会发现多个目标文件包含CDummyMessage::ObjCount1
的定义。