[][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 0 are run first (in unspecified order), then functions with priority number 1 are run ... then functions with priority number 65535 and finaly constructors with no priority.

Safety

Constructor functions must be unsafe. Any access to non data initialized with an equal or lower priority (priority number larger) will cause undefined behavior. (NB: 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 bellow 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 100.