我遇到了一个小问题,我知道其原因,但不知道其解决方案。
我有一个小的单例类,其头文件是
#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'
我知道它是因为我两次导入相同的 header - 我该如何绕过它? _singletone
是静态的并且必须保持静态。
为什么包含守卫没有帮助?
最佳答案
_singleton
是类的 static
成员,您需要在类声明之外显式定义它。如果您在 header 中这样做 - 正如您所做的那样 - 并将该 header 包含在多个源文件中,链接器会找到同一符号的多个定义,因此会提示。所以解决办法就是把这个静态成员定义移到对应的源文件中。
关于c++ - `Scheduler::_singleton' 的多重定义,导入 header 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10367750/