|
| 1 | +## #[used] |
| 2 | + |
| 3 | +The `#[used]` attribute can only be applied to `static` variables. This attribute forces the |
| 4 | +compiler to keep the variable in the output object file (.o, .rlib, etc.) even if the variable is |
| 5 | +not *used*, or referenced, by any other item in the crate. Without this attribute the compiler is |
| 6 | +free to remove variable if it's *unused*, or dead, when optimizations are enabled. |
| 7 | + |
| 8 | +Below is an example that shows under what conditions the compiler keeps a `static` variable in the |
| 9 | +output object file. |
| 10 | + |
| 11 | +``` rust |
| 12 | +// foo.rs |
| 13 | + |
| 14 | +#![feature(used)] |
| 15 | + |
| 16 | +// kept because of #[used] |
| 17 | +#[used] |
| 18 | +static FOO: u32 = 0; |
| 19 | + |
| 20 | +// removed because it's unused |
| 21 | +#[allow(dead_code)] |
| 22 | +static BAR: u32 = 0; |
| 23 | + |
| 24 | +// kept because it's referenced by a *public*, reachable function |
| 25 | +pub static BAZ: u32 = 0; |
| 26 | + |
| 27 | +pub static QUUX: u32 = 0; |
| 28 | + |
| 29 | +pub fn quux() -> &'static u32 { |
| 30 | + &QUUX |
| 31 | +} |
| 32 | + |
| 33 | +// removed because it's referenced by a private, unused (dead) function |
| 34 | +static CORGE: u32 = 0; |
| 35 | + |
| 36 | +#[allow(dead_code)] |
| 37 | +fn corge() -> &'static u32 { |
| 38 | + &CORGE |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +``` console |
| 43 | +$ # with optimizations |
| 44 | +$ rustc -O --emit=obj --crate-type=rlib foo.rs |
| 45 | + |
| 46 | +$ nm -C foo.o |
| 47 | +0000000000000000 R foo::BAZ |
| 48 | +0000000000000000 r foo::FOO |
| 49 | +0000000000000000 R foo::QUUX |
| 50 | +0000000000000000 T foo::quux |
| 51 | + |
| 52 | +$ # without optimizations |
| 53 | +$ rustc --emit=obj --crate-type=rlib foo.rs |
| 54 | + |
| 55 | +$ nm -C foo.o |
| 56 | +0000000000000000 r foo::BAR |
| 57 | +0000000000000000 R foo::BAZ |
| 58 | +0000000000000000 r foo::FOO |
| 59 | +0000000000000000 R foo::QUUX |
| 60 | +0000000000000000 T foo::quux |
| 61 | +0000000000000000 r foo::CORGE |
| 62 | +``` |
0 commit comments