error LNK2005:

来源:百度知道 编辑:UC知道 时间:2024/06/21 08:54:03
在文件elevatorclass.h中声明
#ifndef ELEVATORCLASS_H
#define ELEVATORCLASS_H
#include <iostream.h>
class Elevator
{
private:
int CurrentFloor;
void Move(int);
public:
Elevator();
Elevator(int);
~Elevator();
void Call(int);
void Select(int);
static int Count;
};
int Elevator::Count = 0;
#endif

在文件elevatordef.cpp中定义各个函数
在文件elevatormain.cpp中使用
在链接的时候却出现错误
elevatormain.obj : error LNK2005: "public: static int Elevator::Count" (?Count@Elevator@@2HA) already defined in elevatordef.obj
Debug/xu.exe : fatal error LNK1169: one or more multiply defined symbols found

这是为什么?该怎么解决,我不是已经设置了防止文件重复加入的预处理命令来吗,怎么还出现说already defined 呢,谢谢各位大侠了

初始化放到cpp文件中,防重复是针对单个cpp文件的,只能防止一个cpp文件中重复包含同一个h文件,不同的cpp文件包含同一个头文件是没有问题的,因此编译后会在多个obj文件中有同一个变量定义,连接时产生重复定义的错误。

或者这样定义:

__declspec(selectany) int Elevator::Count = 0;