我遇到了一个小问题,我知道它的原因,但不是它的解决方案。
我有一个小的单例类,其头文件是
#ifndef SCHEDULER_H_
#define SCHEDULER_H_
#include <setjmp.h>
#include <cstdlib>
#include <map>
#include <sys/time.h>
#include <signal.h>
#include "Thread.h"
class Scheduler {
public:
static Scheduler * instance();
~Scheduler();
int threadSwitcher(int status, bool force);
Thread * findNextThread(bool force);
void runThread(Thread * nextThread, int status);
void setRunThread(Thread * thread);
void setSleepingThread(Thread * thread);
void setTimer(int num_millisecs);
std::map<int, Thread *> * getSuspendedThreads() const;
std::map<int, Thread *> * getReadyThreads() const;
Thread * getSleepingThread() const;
Thread * getRunningThread() const;
Thread * getThreadByID(int tid) const;
const itimerval * getTimer() const;
const sigset_t * getMask() const;
void pushThreadByStatus(Thread * thread);
Thread * extractThreadByID(int tid);
private:
Scheduler();
sigset_t _newMask;
sigjmp_buf _image;
static Scheduler * _singleton;
std::map<int, Thread *> * _readyThreads;
std::map<int, Thread *> * _suspendedThreads;
Thread *_sleepingThread;
Thread * _runThread;
itimerval _tv;
};
Scheduler * Scheduler::_singleton = 0;
#endif /* SCHEDULER_H_ */
现在我当然在Scheduler.cpp
导入此头文件,但也导入另一个文件other.cpp
问题是在other.cpp中我一直在
../otherfile.cpp:47: multiple definition of `Scheduler::_singleton'
我知道它,因为我导入了两次相同的标题 - 我该如何解决它? _singletone
是静态的,必须保持静态。
为什么包括警卫没有帮助?
答案 0 :(得分:2)
_singleton
是您班级的static
成员,您需要在类声明之外明确定义它。如果你在标题中这样做 - 并且在多个源文件中包含该标题,那么链接器会找到相同符号的多个定义,因此它会抱怨。因此,解决方案是将此静态成员定义移动到相应的源文件。
答案 1 :(得分:1)
将此行移至您的一个CPP文件中:
Scheduler * Scheduler::_singleton = 0;