0

我收到静态数据成员的多个声明的链接错误。我采取了所有必要的预防措施以避免多次包含头文件,但仍然出现错误。

//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
4

1 回答 1

1

将您的CDummyMessage::ObjCount1定义移动到源文件。

标头保护仅保护您的标头不被多次包含在同一个翻译单元中;它们不会阻止它们被不同的翻译单元包含在内。

目前,包含您的dummymessage.h标题的每个翻译单元都在定义CDummyMessage::ObjCount1. 当编译器尝试将所有代码链接在一起时,它会看到多个目标文件包含CDummyMessage::ObjCount1.

于 2013-10-02T18:54:19.917 回答