Как реализовать Singleton в приложении с DLL

У меня есть приложение (в MS Visual Studio), которое содержит 3 проекта:

main (the one that contains the main function) device (models some hardware device) config (contains some configuration for both other projects)

Итак, граф зависимостей:

main depends on device, which depends on config main depends on config

config Проект содержит Singleton, который содержит некоторые параметры конфигурации.

Я решил повернутьdevice проект в DLL. Когда я сделал это, кажется, что у меня есть два экземпляра Синглтона вconfig проект! Я думаю, это классическая проблема, которая может иметь хорошее решение. Так как я могу это исправить?

Я воспроизвел проблему с помощью следующего (относительно небольшого) кода. Конечно, в моем случае есть около 30 проектов, а не только 3. И я хотел бы сделать только 1 DLL (если это возможно).

<code>// config.h
#pragma once
#include <string>
#include <map>
class Config
{
public:
    static void Initialize();
    static int GetConfig(const std::string& name);

private:
    std::map<std::string, int> data;
};

// config.cpp
#include "config.h"

static Config g_instance;

void Config::Initialize()
{
    g_instance.data["one"] = 1;
    g_instance.data["two"] = 2;
}

int Config::GetConfig(const std::string& name)
{
    return g_instance.data[name];
}
</code>
<code>// device.h
#pragma once

#ifdef _DLL
#define dll_cruft __declspec( dllexport )
#else
#define dll_cruft __declspec( dllimport )
#endif

class dll_cruft Device
{
public:
    void Work();
};

// device.cpp
#include "device.h"
#include <iostream>
#include "config.h"

void Device::Work()
{
    std::cout << "Device is working: two = " << Config::GetConfig("two") << '\n';
}
</code>
<code>// main.cpp
#include <iostream>
#include "config.h"
#include "device.h"

int main()
{
    std::cout << "Before initialization in application: one = " << Config::GetConfig("one") << '\n';
    Config::Initialize();
    std::cout << "After initialization in application: one = " << Config::GetConfig("one") << '\n';
    Device().Work();
    std::cout << "After working in application: two = " << Config::GetConfig("two") << '\n';
}
</code>

Выход:

Before initialization in application: one = 0

After initialization in application: one = 1

Device is working: two = 0

After working in application: two = 2

Некоторые пояснения о том, что делает код и почему:

Main application starts The first print is just to show that the singleton is not initialized yet Main application initializes the singleton The first print shows that the initialization worked Main application starts the "hardware device" Inside the DLL, the singleton is not initialized! I expect it to output two = 2 The last print shows that the singleton is still initialized in main application

Ответы на вопрос(3)

Ваш ответ на вопрос