Skip to content

Commit 26d49a1

Browse files
japaricehuss
authored andcommitted
document #[used]
1 parent 0cd2755 commit 26d49a1

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

src/SUMMARY.md

+3
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@
111111

112112
- [Constant Evaluation](const_eval.md)
113113

114+
- [Application Binary Interface](abi.md)
115+
- [#[used]](used.md)
116+
114117
[Appendix: Influences](influences.md)
115118

116119
[Appendix: As-yet-undocumented Features](undocumented.md)

src/abi.md

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Application Binary Interface (ABI)
2+
3+
This section documents (or will document) features that affect the ABI of a Rust program / binary,
4+
rlib, dylib, etc. A (likely incomplete) list of such features is shown below:
5+
6+
- #[used]
7+
- #[no_mangle]
8+
- #[link_section]
9+
- extern "$ABI" fn

src/used.md

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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

Comments
 (0)