2

原因はわかっていますが、解決策はわかりません。

ヘッダーファイルが次の小さなシングルトンクラスがあります

#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'

同じヘッダーを 2 回インポートしたため、それはわかっています。どうすれば回避できますか? _singletone静的であり、静的である必要があります。インクルードガードが役に立たないのはなぜですか?

4

2 に答える 2

3

_singletonはクラスのstaticメンバーであり、クラス宣言の外で明示的に定義する必要があります。ヘッダーでこれを行い、そのヘッダーを複数のソースファイルに含めると、リンカは同じシンボルの複数の定義を見つけるため、文句を言います。したがって、解決策は、この静的メンバーの定義を対応するソース ファイルに移動することです。

于 2012-04-28T21:44:03.937 に答える
1

この行を CPP ファイルの 1 つだけに移動します。

Scheduler * Scheduler::_singleton = 0;
于 2012-04-28T21:38:54.133 に答える