89

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.

s3rvac
  • 9,301
  • 9
  • 46
  • 74

2 Answers2

101

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":

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • The last link (profiling rust code with callgrind) seems to be dead. I could only find this related [reddit post](https://www.reddit.com/r/rust/comments/3n5ann/profiling_rust_code_with_callgrind/), which contains the same dead link. – MB-F May 24 '18 at 19:12
  • This actually produces a fat binary, is there a way of producing the debugging symbols but yet being able to have a thin binary. I have a 9MB .a file and this setting takes it to 40MB – Pacu Sep 25 '20 at 14:34
  • 1
    @Pacu that's not related to this question. Splitting debug info to a separate location is platform-specific. See [Will debug symbols affect the performance in Rust?](https://stackoverflow.com/a/62998579/155423) – Shepmaster Sep 28 '20 at 13:44
  • 2
    Another way to set the same parameter is through the `CARGO_PROFILE_RELEASE_DEBUG` environment variable. You can set that to "true". – rubdos Apr 09 '22 at 08:11
81

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

$ RUSTFLAGS=-g cargo build --release
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
s3rvac
  • 9,301
  • 9
  • 46
  • 74