Well, I’m not a fan of global constructors, but the existence of rust-ctor
illustrates the danger of taking useful functionality from C/C++ and refusing to implement it. In a language as flexible as Rust, someone will implement it anyway, but without the benefit of the compiler knowing what’s going on, often resulting in brokenness.
FWIW, it should be possible to implement inventory
without using global constructors. rust-ctor
works by placing statics in a specially-named section to invoke OS-specific functionality that automatically treats them as pointers to initialization routines. But you could also put statics in an arbitrarily-named section and use OS-specific functionality to get the beginning and end of that section at runtime:
- Playground link that works on Linux and anything else using a GNU linker, plus Darwin
- Should be possible on Windows too based on this Stack Overflow answer
That way you can have a function iterate over all the statics in the program that are declared in that section, with no need to run code before main
.
In theory, it should also be possible for rustc to implement a version of this “put me in a list” operation itself, based on the metadata embedded in rlibs and Rust dylibs, rather than having to rely on OS-specific constructs.
Edit: The above won’t work with dylibs, though, since you’ll only see the symbols defined within your own dylib. A metadata-based native Rust version wouldn’t have that limitation.