How to initialize a shared library on Linux

拜拜、爱过 提交于 2019-11-30 03:53:48

In C++ under Linux, global variables will get constructed automatically as soon as the library is loaded. So that's probably the easiest way to go.

If you need an arbitrary function to be called when the library is loaded, use the constructor attribute for GCC:

__attribute__((constructor)) void foo(void) {
    printf("library loaded!\n");
}

Constructor functions get called by the dynamic linker when a library is loaded. This is actually how C++ global initialization is implemented.

If you want your code to be portable you should probably try something like this:

namespace {
  struct initializer {
    initializer() {
      std::cout << "Loading the library" << std::endl;
    }

    ~initializer() {
      std::cout << "Unloading the library" << std::endl;
    }
  };
  static initializer i;
}

Using a global (or a local-static wrapped up in a function) is nice... but then you enter the land of static initialization fiasco (and the actual destruction is not pretty either).

I would recommend to have a look at the Singleton implementation of Loki.

There are various lifetime policies, one of which is Phoenix and will help you avoid this fiasco.

When you are at it, read Modern C++ Design which explains the problems encountered by the Singleton in depth as well as the uses for the various policies.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!