仅用cpp编写的类的导出问题

问题描述 投票:0回答:1

我有两个项目,一个是可执行文件(app),另一个是静态/共享库(lib)。

在lib项目中,我的结构如下所示:


// lib proj interface
class Entity
{

};

class EntitySystem
{
public:
    virtual void update() = 0;
};

class EventSystem
{
public:
    static bool register_update_system(IEntitySystem* system){...}
    void update()
    {
        // for each entity, call system->update(entity);
    }
};

然后我只在.cpp文件中实现系统并使用静态方法来注册我的更新函数,例如:


// timersystem.cpp
class TimerSystem: public EntitySystem
{
public:
    void update(TimerEntity& entity) override
    {
        ...
    }
};

bool _ = EventSystem::register_update_system(new TimerSystem());

但是,在构建并运行应用程序后,

bool _ = EventSystem::register_update_system(new TimerSystem());
行似乎没有执行。换句话说,TimerSystem没有正确注册到应用程序项目中的EventSystem中。我该如何解决这个问题?非常感谢。

c++ oop design-patterns dll entity
1个回答
0
投票

您面临的问题可能与静态初始化顺序问题有关。当不同翻译单元(源文件)中有全局对象时,无法保证它们初始化的顺序。在您的情况下, bool _ = EventSystem::register_update_system(new TimerSystem()); 行是全局对象初始化的一部分。

为了确保 TimerSystem 在使用前正确注册,您可以考虑使用函数进行注册,并在应用程序开始时显式调用该函数。这样,您就可以控制注册顺序。

这是一个例子:

// timersystem.cpp
class TimerSystem : public EntitySystem
{
public:
    void update(TimerEntity& entity) override
    {
        // ...
    }
};

// Register function for TimerSystem
void registerTimerSystem()
{
    bool _ = EventSystem::register_update_system(new TimerSystem());
}

// main.cpp in the app project
int main()
{
    // Register the TimerSystem before using it
    registerTimerSystem();

    // Your application logic here

    return 0;
}

通过在 main 函数中显式调用 registerTimerSystem(),您可以确保注册发生在执行过程中的已知点,并且不太可能遇到静态初始化顺序问题。

请记住,依赖全局对象和静态初始化顺序可能会导致微妙的问题,通常建议尽量减少使用具有复杂初始化依赖项的全局对象。

© www.soinside.com 2019 - 2024. All rights reserved.