[][src]Attribute Macro ctor::ctor


Marks a function as a library/executable constructor. This uses OS-specific linker sections to call a specific function at load time.

Multiple startup functions are supported, but the invocation order is not guaranteed.


Print a startup message:

fn foo() {
  println!("Hello, world!");


Make changes to static variables:

static INITED: AtomicBool = ATOMIC_BOOL_INIT;

fn foo() {
  INITED.store(true, Ordering::SeqCst);


The #[ctor] macro makes use of linker sections to ensure that a function is run at startup time.

The above example translates into the following Rust code (approximately):

 #[cfg_attr(target_os = "linux", link_section = ".ctors")]
 #[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")]
 #[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
 static foo: extern fn() = {
   extern fn foo() { /* ... */ };