5

I have the following problem: I use some classes like the following to initialize C libraries:

class Hello
{
public:
  Hello()
  {
    cout << "Hello world" << endl;
  }

  ~Hello()
  {
    cout << "Goodbye cruel world" << endl;
  }

} hello_inst;

If I include this code in a hello.cc file and compile it together with another file containing my main(), then the hello_inst is created before and destroyed after the call to main(). In this case it just prints some lines, in my project I initialize libxml via LIBXML_TEST_VERSION.

I am creating multiple executables which share a lot of the same code in a cmake project. According to this thread: Adding multiple executables in CMake I created a static library containing the code shown above and then linked the executables against that library. Unfortunately in that case the hello_inst is never created (and libxml2 is never initialized). How can I fix this problem?

Community
  • 1
  • 1
hfhc2
  • 4,182
  • 2
  • 27
  • 56

3 Answers3

1

I had a similar problem and solved it by defining my libraries as static. Therefore I used the following code:

add_library( MyLib SHARED ${LBMLIB_SRCS} ${LBMLIB_HEADER})

Maybe this fixes your problem

tune2fs
  • 7,605
  • 5
  • 41
  • 57
  • Well, if I would ship/install the programs, I would have to install the library as well, wouldn't I? – hfhc2 May 31 '13 at 13:59
  • Yes, that is the drawback of this method. But I had a similar problem and did not found another solution. – tune2fs May 31 '13 at 14:16
0

There is no official way of forcing shared libraries global variables to be initialised by the standard and is compiler dependent.

Usually this is done either the first time something in that library is actually used (A class, function, or variable) or when the variable itself is actually used.

If you want to force hello_inst to be used, call a function on it, then see if and when the constructor and destructors are called.

Read this thread for more information: http://www.gamedev.net/topic/622861-how-to-force-global-variable-which-define-in-a-static-library-to-initialize/

Salgar
  • 7,687
  • 1
  • 25
  • 39
  • Well, but then I might as well initialize the library in my main(), the idea was to use RAII... – hfhc2 May 31 '13 at 13:13
0

As far as I'm aware, statics defined in library should be constructed before main is called and destroyed after main, in the manner you describe. Indeed I have used shared libraries in many projects, and have never encountered the problems you describe. I understand a library file, to be little more than a container of object files. However, that said.....

If your code does nothing with the object that is created, the linker is free to remove it (dead code removal). I would suggest making sure the static object is referenced. Call a member function, perhaps?