In C++ it's possible to call arbitrary functions at init time before main()
has been entered, including calls to libraries that are not fully initialized yet, which can cause confusing errors. If I'm writing a library, is it possible in standard modern C++ (C++20 or so) to tell whether main()
has started yet, so I can prevent the user of the library from using it before it's safe?
Considered solutions:
- Having a
library::init()
function called at the beginning ofmain()
. The library already works fine without aninit()
, so it seems silly to add one just to improve error reporting. If nothing else works, obviously this is the best solution. - Using a static initializer to determine when it's safe to use the library. It cannot be predicted what order static initializers run in, so this is not reliable.
- Using a function-level static variable to initialize the library (essentially lazy initialization) so that initialization order doesn't matter. I already do this for some things, but this can't extend the protection to other libraries or system resources that are not usable before
main()
. - Walking up the stack manually to find a frame for
main()
. I think not. : )