How to initialize a shared library on Linux

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;
}

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.