If I build a Rust application using Cargo with some crate dependencies, will any code in those dependencies that is unused by my application be eliminated from the final executable?
-
I think yes, but I'm not sure. – Stargateur Aug 28 '18 at 11:49
-
I could probably check with objdump or something similar but I want to see if there's a definitive answer or if it's planned for a future release. There's a related issue with the size of hello-world type executables. – Thomas Bratt Aug 28 '18 at 11:50
-
1With LTO for sure, otherwise I'm not that certain. – hellow Aug 28 '18 at 11:51
2 Answers
It looks like it. I made a test lib and bin crate side by side:
// hellobin/src/main.rs
extern crate hellolib;
fn main() {
hellolib::func1();
}
For the lib:
// hellolib/src/main.rs
pub fn func1() {
println!("Hello, world!");
}
pub fn func2() {
println!("Hello, other world!");
}
Building my binary and then inspecting symbols with nm
:
$ nm target/debug/helloworld | grep hello
0000000100001360 t __ZN10helloworld4main17h749f61fb726f0a10E
00000001000014b0 T __ZN8hellolib5func117hec0b5301559d46f6E
Only the used function has a symbol in the final binary.
You can compile with cargo rustc -- -C link-dead-code
though and you will see both symbols are present, including the unused one:
$ nm target/debug/helloworld | grep hello
0000000100001270 t __ZN10helloworld4main17h3104b73b00fdd798E
00000001000013d0 T __ZN8hellolib5func117hec0b5301559d46f6E
0000000100001420 T __ZN8hellolib5func217hc9d0886874057b84E
I believe (but I'm not sure) that it's the linker removing the dead code, so it may have still been compiled and then removed during linking.

- 388,571
- 95
- 1,107
- 1,366

- 13,381
- 6
- 48
- 66
-
Nice :) I'll accept that as the answer unless someone comes up with something definitive from the rust docs/project. – Thomas Bratt Aug 28 '18 at 12:31
TL;DR: Yes, every unused function is going to be excluded.
This is actually the job of LLVM that will at least keep track of every unused function. Any unused code (as in codepaths in function not taken across the entire Application) may require LTO (Link Time Optimizations) to be activated to turn your crate into one compilation unit and give LLVM a fighting chance.

- 1,202
- 12
- 10
-
I edited the answer to clarify that the `tl;dr yes` refers to unused functions in particular. – Markus Klein Aug 28 '18 at 14:48