1 unstable release

Uses old Rust 2015

0.1.0 Apr 16, 2017

#11 in #initializer

MIT/Apache

4KB
58 lines

constructor

Adds a macro for static initialization.


lib.rs:

Registers a function to be called before main (if an executable) or when loaded (if a dynamic library). Using this is a bad idea. You can do this in a way that isn't abysmally fragile.

Example

pub static mut X: usize = 0;

extern fn init() {
    unsafe { X = 5; }
}
constructor! { init }


fn main() {
   assert_eq!(unsafe { X }, 5);
}

Caveats

This isn't exactly portable, though the implementation is quite simple.

Doing anything particularly complicated, such IO or loading libraries, may cause problems on Windows. (?)

Every parent module must be public. If it is not, then it will be stripped out by --release. At least the compiler gives a helpful warning.

Beware, for some say that these techniques can unleash a terrible evil. lazy_static may be a more appropriate tool.

No runtime deps