2

I'm having a little problem I know its cause but not its solution.

I have a small singleton class whose header file is

#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_ */

Now of course I import this header file in Scheduler.cpp, but also in another file other.cpp

The problem is that in other.cpp I keep getting

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

I know its because I import the same header twice - how do I go around it? _singletone is static and must remain static. And how come the include guards don't help?

yotamoo
  • 5,334
  • 13
  • 49
  • 61
  • In the answer to [this question](http://stackoverflow.com/questions/10340515/wunused-variable-warning) I suggested you put the definition of `Scheduler::_singleton` in the implementation file. I think that will fix the problem. – juanchopanza Apr 28 '12 at 21:45

2 Answers2

4

_singleton is a static member of your class and you need to define it explicitly outside of the class declaration. If you do so in the header - as you did - and include that header in multiple source files, linker finds multiple definitions of the same symbol and therefore it complains. So the solution is to move this static member definition to the corresponding source file.

Bojan Komazec
  • 9,216
  • 2
  • 41
  • 51
1

Move this line to exactly one of your CPP files:

Scheduler * Scheduler::_singleton = 0;
Robᵩ
  • 163,533
  • 20
  • 239
  • 308