I have a function that I would like to call before my main
function in rust:
fn init_stuff() {
// do stuff
}
and I was just wondering if there was any equivalent to the __attribute__((constructor))
and __attribute__((destructor))
methods that GCC has to execute the initialization functions and destruction functions. Or will I have to call them all in main
?
Rust intentionally does not provide any "before main" functionality as a way to avoid the static initialization order fiasco. See this old FAQ.
The alternative is generally to use lazy-initialization - i.e. don't run initialization logic until you need it. This can be done with a static LazyLock
, OnceLock
, or Once
.
If instead your goal is to provide registration, the general guidance is to do so explicitly. Otherwise, the inventory or linkme crates may help. These crates safely avoid "before main" issues with the Rust runtime (as you might encounter with the ctor crate) by forcing user code to be const
.
I do not know of any safe "after main" alternatives.