How to get a release build with debugging information when using cargo?

RustRust Cargo

Rust Problem Overview


The following command

$ cargo build

produces a non-optimized build with debugging information. On the contrary,

$ cargo build --release

produces an optimized build without debugging information.

Is there a way of producing an optimized build with debugging information? I need this to get meaningful profiling information.

Rust Solutions


Solution 1 - Rust

As of Rust 1.57, Cargo now allows for custom profiles. This allows you to define your own profile that adds debug information:

[profile.release-with-debug]
inherits = "release"
debug = true

You can then use that profile when building:

% cargo build --profile=release-with-debug
   Compiling buggin v0.1.0 (/tmp/buggin)
    Finished release-with-debug [optimized + debuginfo] target(s) in 0.48s

Prior to this version, or if you always wanted to have debugging information, you can modify the release profile to include debugging symbols:

[profile.release]
debug = true

Note that the release profile and the bench profile differ.

See also

Or basically any of the top search results for "rust profiling":

Solution 2 - Rust

Another option that I found that does not require changing Cargo.toml is to use the RUSTFLAGS environment variable:

$ RUSTFLAGS=-g cargo build --release

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questions3rvacView Question on Stackoverflow
Solution 1 - RustShepmasterView Answer on Stackoverflow
Solution 2 - Rusts3rvacView Answer on Stackoverflow