[][src]Attribute Macro static_init::constructor

#[constructor]

Attribute for functions run at program initialization (before main)

#[constructor]
fn initer () {
// run before main start
}

The execution order of constructors is unspecified. Nevertheless on ELF plateform (linux,any unixes but mac) and windows plateform a priority can be specified using the syntax constructor(<num>) where <num> is a number included in the range [0 ; 216-1].

Constructors with priority number 65535 are run first (in unspecified order), then constructors with priority number 65534 are run ... then constructors with priority number 0 and finaly constructors with no priority.

Safety

Constructor functions must be unsafe. Any access to "dynamic" statics with an equal or lower initialization priority will cause undefined behavior. (NB: usual static data initialized by a const expression are always in an initialized state so it is always safe to read them)

Notably, on Elf platforms, accesses to std::env::* with a priority number above 65535-100 will cause undefined behavior. On windows accessing std::env::* will never causes undefined behavior. On other plateforms any access to std::env::* in a constructor, whatever its priority, will cause undefined behavior. In this last case, the information may be accessible in the /proc/self directory.

#[constructor(0)]
unsafe fn first () {
// run before main start
}

#[constructor(1)]
unsafe fn then () {
// run before main start
}

NB: Whatever the priority constructors are run after initialization of libc resources. C++ static objects are initialized as constructors with no priorities. On ELF plateform libstdc++ resources are initialized with priority 65535-100.