1

I'm working on a cross platform project (linux-GCC, windows-Mingw-64). In a shared library I have some singleton classes defined like this:

class S {
public:
  static S& getInstance() {
    static S instance;
    return (instance);
  }

  void setSomething(int i) {
    this->i = i;
   }

  int getSomething() {
    return (this->i);
  }

private:
  S() : i(0) {}

  int i;
}

In another project that uses this shared library where S is defined, I declare the following class.

Class A {
public:
  void doSomething() {
    s.setSomething(42);
  }

private:
  S& s = S::getInstance();
}

In the main I use the class A to set "something" with S, and S itself to get "something", like this:

int main() {
  A a;

  a.doSomething();

  S& s = S::getInstance();

  printf("i: %d\n", s.getSomething());  // expected to print 42, but on windows it prints 0

  return (0);
}

On linux there is no problem, but on windows the S instances are different. Why windows version does not work? How can I fix it?

EDIT (mark as duplicated):

Cross platform shared library singleton

I have added "__declspec(dllexport)" before the "getInstance" method. (In the related question is used as DLL_EXPORT but I cannot find this declaration anywhere) After that mingw generates an almost empty ".a" file and the projects using it throws a bunch of "undefined reference" related to the library.

Where can I find a good documentation about this behavior? I don't want just the code solution, (I'd still appreciate it.) I want to know why is this happening.

Ludovicio
  • 135
  • 1
  • 6

0 Answers0