user569298
user569298

Reputation: 1

Global variables reset when loading a shared library

I'm currently working on an application which loads a shared library that contains a global store of operations (this is a simplified view of the feature). In a very simplified view, this is what I've got:

The shared libary has a class which registers the operations in the store and looks something similar to:

// Factory.h

class Factory
{
public:
    typedef void (*FuncPtr)();
    typedef std::multimap<std::string, FuncPtr> StoreType;  

 static void Register(const std::string& name, FuncPtr func)
 {
  m_Store.insert(std::pair<std::string, FuncPtr>(name, func));

  using namespace std;
  cout << "*** Count: " << ++Count << ", Size: " << m_Store.size() << endl;
 }  

public:  
    static StoreType m_Store;  
    static int Count;  
};


struct Register
{
    Register(const std::string& name, Factory::FuncPtr func)
    {
        Factory::Register(name, func);
    }
};



// Factory.cpp
#include "Factory.h"

Factory::StoreType Factory::m_Store;
int Factory::Count = 0;

There are also several .cpp files within the library which registers operations. Registration occurs as:

void Func()
{
... // some operation
}

Register obj("name", Func);

When executing the main application the library is loaded as a dependency. The main application itself has some .cpp which registers operations.

The output I get when I run this code is:
--- Count: 1, Size: 1
--- Count: 2, Size: 2
--- Count: 3, Size: 3
--- Count: 4, Size: 4
--- Count: 5, Size: 1
--- Count: 6, Size: 2
--- Count: 7, Size: 3
--- Count: 8, Size: 4
--- Count: 9, Size: 5
--- Count: 10, Size: 6
--- Count: 11, Size: 7
--- Count: 12, Size: 8

Notice how the size of the std::multimap is reset after the shared library is loaded!

Also, when I used a std::map instead of a std::multimap I get a segmentation fault at: _ZSt18_Rb_tree_decrementPSt18_Rb_tree_node_base from libstdc++.so.6

To help debug the problem I wrote a simplified version of the above and it works as expected so I'm assuming there's a issue with our main application but I don't really know where. I've looked at the compiler and linker options and ensured the test application has the same settings.

Development environment:
lucid build g++ version 4.4.3

If anyone has any ideas please help.

Upvotes: 0

Views: 616

Answers (1)

linuxbuild
linuxbuild

Reputation: 16133

I just want to say that your example is working fine in my environment (using multimap or map data types):

*** Count: 1, Size: 1
*** Count: 2, Size: 2
*** Count: 3, Size: 3
*** Count: 4, Size: 4
*** Count: 5, Size: 5
*** Count: 6, Size: 6
*** Count: 7, Size: 7
*** Count: 8, Size: 8
*** Count: 9, Size: 9
*** Count: 10, Size: 10
*** Count: 11, Size: 11
*** Count: 12, Size: 12

Environment: OpenSUSE-11.3, g++ 4.5.0, libstdc++.so.6.0.14

Try to check max_size() of your map and check error code of insert() on each call.

Upvotes: 0

Related Questions