多次定义"调度程序::_singleton",导入标头两次
multiple definition of `Scheduler::_singleton', importing header twice
我遇到了一个小问题,我知道它的原因,但不知道它的解决方案。
我有一个小型单例类,其头文件是
#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;
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- Qt插槽调用了两次
- 做 std::用相同的unique_ptr移动两次
- C++两次定义相同的函数会导致错误
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 对于优化级别为 0 的 std::vector,析构函数被调用两次
- 使用柯南打包时如何避免列出两次依赖?
- 为什么要执行两次位移((x >> 4)<< 4)?
- 对结构向量进行两次排序
- 如果我使用同一个密钥推送用户数据两次,会发生什么
- Singleton:析构函数怎么能被调用两次