Warren Seine
Warren Seine

Reputation: 2449

Invoke code without an entry point

In C++, I'd like to be able to simulate "plugins" without dynamic library loading. I found a way to hook up a function inside a static library to my executable without referencing it, but I'm unsure this is correct.

Because global symbols are initialised before the translation unit main function, I may write something like:

int _ = []()
{
    std::cout << "hook" << std::endl;
    return 0;
} ();

The combination of lambda + IIFE pattern + safe initialisation works, but since I've never encountered that kind of technique, I'm worried about undefined behaviours or compiler-specific details. Is there anything better?

Upvotes: 2

Views: 80

Answers (1)

Praxeolitic
Praxeolitic

Reputation: 24049

What you show is legal C++. In general, initialization of global variables can be used to run code outside of main(). There are caveats, namely the "static initialization order fiasco" -- as mentioned in the link you provide.

You haven't seen it because it's frowned upon. You're using global variables to run code outside of main(). Many such attempts have ended in frustration.

Upvotes: 0

Related Questions