Search code examples
c++initializationraii

How to execute an auto-setup function


While working on a library depending on another third party library, I ran into the problem that the third party library is absolutely trash requires a manual call to a global setup and cleanup function.

int main()
{
    setup();
    //do stuff
    cleanup();
}

Now, this is a total sh*t show not much of a problem in application code since it is just syntactically horrifying, but is actually a pain in a library.

The library is supposed to abstract these weird implementation details away, and requiring the user to call a setup function is like slapping my own face.

I tried to make them disappear

//namespace scope
struct AutoMagic
{
    AutoMagic() {setup();}
    ~AutoMagic() {cleanup();}
};
AutoMagic automagic;

And then I realized this won't work across translation units as seen here and there

Thus the question in the title.


Solution

  • In the end, the only viable thing left is unportable compiler specific code

    AutoMagic automagic __attribute__((init_priority(420));
    

    Unportable as in, basically all mainstream compilers support this except msvc.

    This attribute forces the variable to be initialized before all variables without this attribute and those with priority number greater than this variable.

    This goes to illustrate that there is indeed a demand for initialization priority guarantees and that it is obviously still not being given by the standard.