3 The tracking issue for this feature
4 is: [40289](https://github.com/rust-lang/rust/issues/40289).
6 ------------------------
8 The `#[used]` attribute can be applied to `static` variables to prevent the Rust
9 compiler from optimizing them away even if they appear to be unused by the crate
10 (appear to be "dead code").
23 If you compile this program into an object file, you'll see that `FOO` makes it
24 to the object file but `BAR` doesn't. Neither static variable is used by the
28 $ rustc -C opt-level=3 --emit=obj used.rs
31 0000000000000000 T main
33 0000000000000000 r used::FOO
34 0000000000000000 t used::main
37 Note that the *linker* knows nothing about the `#[used]` attribute and will
38 remove `#[used]` symbols if they are not referenced by other parts of the
42 $ rustc -C opt-level=3 used.rs
44 $ nm -C used | grep FOO
47 "This doesn't sound too useful then!" you may think but keep reading.
49 To preserve the symbols all the way to the final binary, you'll need the
50 cooperation of the linker. Here's one example:
52 The ELF standard defines two special sections, `.init_array` and
53 `.pre_init_array`, that may contain function pointers which will be executed
54 *before* the `main` function is invoked. The linker will preserve symbols placed
55 in these sections (at least when linking programs that target the `*-*-linux-*`
61 extern "C" fn before_main() {
62 println!("Hello, world!");
65 #[link_section = ".init_array"]
67 static INIT_ARRAY: [extern "C" fn(); 1] = [before_main];
72 So, `#[used]` and `#[link_section]` can be combined to obtain "life before
76 $ rustc -C opt-level=3 before-main.rs
82 Another example: ARM Cortex-M microcontrollers need their reset handler, a
83 pointer to the function that will executed right after the microcontroller is
84 turned on, to be placed near the start of their FLASH memory to boot properly.
86 This condition can be met using `#[used]` and `#[link_section]` plus a linker
90 #![feature(lang_items)]
95 extern "C" fn reset_handler() -> ! {
99 #[link_section = ".reset_handler"]
101 static RESET_HANDLER: extern "C" fn() -> ! = reset_handler;
103 #[lang = "panic_fmt"]
110 FLASH : ORIGIN = 0x08000000, LENGTH = 128K
111 RAM : ORIGIN = 0x20000000, LENGTH = 20K
116 .text ORIGIN(FLASH) :
119 LONG(ORIGIN(RAM) + LENGTH(RAM)); /* initial SP value */
120 KEEP(*(.reset_handler));
122 /* Omitted: The rest of the vector table */
129 /* Unused unwinding stuff */
136 $ xargo rustc --target thumbv7m-none-eabi --release -- \
137 -C link-arg=-Tlink.x -C link-arg=-nostartfiles
139 $ arm-none-eabi-objdump -Cd target/thumbv7m-none-eabi/release/app
140 ./target/thumbv7m-none-eabi/release/app: file format elf32-littlearm
143 Disassembly of section .text:
145 08000000 <app::RESET_HANDLER-0x4>:
146 8000000: 20005000 .word 0x20005000
148 08000004 <app::RESET_HANDLER>:
149 8000004: 08000009 ....
151 08000008 <app::reset_handler>:
152 8000008: e7fe b.n 8000008 <app::reset_handler>