LICENSE LICENSE Documentation Crates.io Version

Module initialization termination function with priorities and (mutable) statics initialization with non const functions.

Minimum rust version required: 1.49

Functionalities

Example

```rust use static_init::{constructor,destructor,dynamic};

#[constructor] unsafe extern "C" fn doinit(){ } //Care not to use priorities above 65535-100 //as those high priorities are used by //the rust runtime. #[constructor(200)] unsafe extern "C" fn dofirst(){ }

#[destructor] unsafe extern "C" fn finaly() { } #[destructor(100)] unsafe extern "C" fn ultimately() { }

#[dynamic] static V: Vec = unsafe{vec![1,2,3]};

#[dynamic(init,drop)] static mut V1: Vec = unsafe{vec![1,2,3]};

//Initialized before V1 //then destroyed after V1 #[dynamic(init=142,drop=142)] static mut INITANDDROP: Vec = unsafe{vec![1,2,3]};

fn main(){ asserteq!(V[0],1); unsafe{ asserteq!(V1[2],3); V1[2] = 42; assert_eq!(V1[2], 42); } } ```

Attributes

All functions marked with the constructor attribute are run before main is started.

All function marked with the destructor attribute are run after main has returned.

Static variables marked with the dynamic attribute can be initialized before main start and optionaly droped after main returns.

The attributes constructor and destructor works by placing the marked function pointer in dedicated object file sections.

Priority ranges from 0 to 216-1. The absence of priority is equivalent to an hypothetical priority of -1.

During program initialization:

Supported platforms

Any platforms where the target executable file format is ELF (unixes: linux, android, bsd, ...), Windows and macos and ios. Webassembly is not supported. Priorities are not supported on macos and ios.

Safety

Functionnalities provided by this library are inherently unsafe. During execution of a constructor, any access to variable initialized with a lower or equal priority will cause undefined behavior. During execution of a destructor any access to variable droped with a lower or equal priority will cause undefined behavior.

This is actually the reason to be of priorities: this is the coder own responsability to ensure that no access is performed to statics with lower or equal priorities.

```rust use static_init::dynamic;

#[dynamic] static V1: Vec = unsafe {vec![1,2,3]};

//potential undefined behavior: V1 may not have been initialized yet #[dynamic] static V2: i32 = unsafe {V1[0]};

//undefined behavior, V3 is unconditionnaly initialized before V1 #[dynamic(1000)] static V3: i32 = unsafe {V1[0]};

#[dynamic(1000)] static V4: Vec = unsafe {vec![1,2,3]};

//Good, V5 initialized after V4 #[dynamic(500)] static V5: i32 = unsafe {V4[0]};

//Good, V6 initialized after V5 and v4 #[dynamic] static V6: i32 = unsafe {*V5+V4[1]}; ```

Comparisons against other crates

lazy_static

ctor

Documentation and details

Mac

ELF plateforms:

Windows