LTO flags are silently ignored if one the crate-type of the root package is not compatible with LTO
Problem
Using the Cargo.toml below, LTO is not used for the staticlib target when building multiple library targets with cargo build --release.
To enable LTO, the lib target must be removed, or we must use cargo rustc --crate-type=staticlib for building separately.
Steps
-
Cargo.toml:
[package]
name = "a"
[profile.release]
lto = true
[lib]
crate-type = ["lib", "staticlib"]
- Command
cargo build --release
Possible Solution(s)
Show a warning that LTO is disabled for the LTO-compatible targets, and suggest using cargo rustc --crate-type=X.
Version
cargo 1.81.0 (2dbb1af80 2024-08-20)
release: 1.81.0
commit-hash: 2dbb1af80a2914475ba76827a312e29cedfa6b2f
commit-date: 2024-08-20
host: x86_64-unknown-linux-gnu
libgit2: 1.8.1 (sys:0.19.0 vendored)
libcurl: 8.8.0-DEV (sys:0.4.73+curl-8.8.0 vendored ssl:OpenSSL/1.1.1w)
ssl: OpenSSL 1.1.1w 11 Sep 2023
os: Ubuntu 20.4.0 (focal) [64-bit]
We have this comment in the code though it lacks an explanation https://github.com/rust-lang/cargo/blob/5e2878f7868ab141e071982fd9c8325142048610/src/cargo/core/compiler/lto.rs#L109-L111
That code seemed to be added in #8349
This is a dup of #2301 and exactly identical to #4611. The core issue is that the compiler rejects multiple crate types that some accepts LTO some don't. https://github.com/rust-lang/cargo/issues/2301#issuecomment-173654991.
Close in favor #4611.