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