I've created simple shared library that contains singleton class and I expect this class to behave accordingly, i.e. it will be a real singleton for all applications that will use it. But in fact it turned out that it works differently. Each application that uses my shared library creates its own instance of singleton which doesn't fit my plan at all.
This is code of the shared library:
singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#if defined _WIN32 || defined __CYGWIN__
#ifdef BUILDING_DLL
#ifdef __GNUC__
#define DLL_PUBLIC __attribute__ ((dllexport))
#else
#define DLL_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax.
#endif
#else
#ifdef __GNUC__
#define DLL_PUBLIC __attribute__ ((dllimport))
#else
#define DLL_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax.
#endif
#endif
#define DLL_LOCAL
#else
#if __GNUC__ >= 4
#define DLL_PUBLIC __attribute__ ((visibility ("default")))
#define DLL_LOCAL __attribute__ ((visibility ("hidden")))
#else
#define DLL_PUBLIC
#define DLL_LOCAL
#endif
#endif
class DLL_PUBLIC Singleton
{
public:
static Singleton &instance();
int test();
private:
Singleton();
int m_num;
};
#endif
singleton.cpp
#include "singleton.h"
Singleton &Singleton::instance()
{
static Singleton singleton;
return singleton;
}
Singleton::Singleton() :
m_num(0)
{ }
int Singleton::test()
{
return ++m_num;
}
compiling and linking as following:
g++ -c -pipe -fPIC -o singleton.o singleton.cpp
g++ -rdynamic -export-dynamic -shared -Wl,-soname,libSingletonLib.so.1 -o libSingletonLib.so.1.0.0 singleton.o
Small testing utility:
main.cpp
#include <stdio.h>
#include "singleton.h"
int main(int argc, char *argv[])
{
int num = Singleton::instance().test();
printf("num: %d", num);
getchar();
return 0;
}
and compiling and linking options:
g++ -c -pipe -g -std=gnu++11 -Wall -W -fPIC -o main.o main.cpp
g++ -Wl -o ../SingletonTest main.o -L.. -lSingletonLib
Now I run 2 instances of the test application and so I expect both of them will use the singleton and the number will increment. But unexpectedly the output is:
first instance:
./SingletonTest
num: 1
second instance:
./SingletonTest
num: 1
Note: the first application still runs when the second one started.
As I understand each instance of the application creates different instance of the singleton.
How can I avoid this situation so all the instances that had linked with the same shared library will use the only one singleton?
I use:
Ubuntu 18.04
gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
Update: Ok, it looks that I have to use shared memory or some interprocess communication. I've never worked with that before so I'll rephrase the question: How can I use the one and only one singleton for several process? How can I put it in shared memory or whatever?