多次定义"调度程序::_singleton",导入标头两次

multiple definition of `Scheduler::_singleton', importing header twice

本文关键字:两次 singleton 调度程序 定义 导入      更新时间:2023-10-16

我遇到了一个小问题,我知道它的原因,但不知道它的解决方案。

我有一个小型单例类,其头文件是

#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

问题是在其他方面.cpp我不断得到

../otherfile.cpp:47: multiple definition of `Scheduler::_singleton'

我知道这是因为我两次导入相同的标头 - 我该如何绕过它? _singletone是静态的,必须保持静态。为什么包括警卫没有帮助?

_singleton 是类的static成员,您需要在类声明之外显式定义它。如果在标头中执行此操作(就像您所做的那样(,并将该标头包含在多个源文件中,链接器会找到同一符号的多个定义,因此它会抱怨。因此,解决方案是将此静态成员定义移动到相应的源文件。

将此行移动到您的一个 CPP 文件:

Scheduler * Scheduler::_singleton = 0;