質問

I have several libraries, each of which implement a class (derived from QObject). I would like each of these libraries to execute a function the first time they load. I found a couple of similar questions here:

Automatically executed functions when loading shared libraries

and

How exactly does __attribute__((constructor)) work?

but any initialization function I create based on the answers never executes. I've tried creating the function in a namespace, outside a namespace (and not a part of my class), using __attribute__((constructor)), naming it _init, and specifying the function name to the linker with:

QMAKE_LFLAGS_RELEASE += -Wl,-init,libinitfunc

None of these have worked.

I should also note that I'm cross-compiling these libraries to run on an embedded ARM device that uses busybox for much of its functionality.

役に立ちましたか?

解決

Since this is C++ code, you shouldn't need C-style hacks.

class LibInstance {
public:
  LibInstance() {
    qDebug() << __FILE__ << "has been initialized";
  }
  ~LibInstance() {
    qDebug() << __FILE__ << "has been unloaded";
  }
}

Q_GLOBAL_STATIC(LibInstance, libInstance)

class LibExecutor {
  LibExecutor() { libInstance(); }
};
static LibExecutor libExecutor;

An instance of LibExecutor is guaranteed to be constructed, in a non-threadsafe way, before main() starts running; or before the library finishes loading, if it's demand-loaded. The LibExecutor's constructor is then using the Q_GLOBAL_STATIC implementation to thread-safely execute the LibInstance's constructor.

It is in LibInstance's constructor that you place the initialization functionality you desire. The destructor will be called when the library is being unloaded.

It is generally safe, cross platform, and used within Qt itself.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top