9

Rust documentation teaches us that cargo build creates a binary file after compiling, which we can execute with cargo run. cargo run will again compile the code if it notices any change after cargo build command is executed. It also says that cargo build --release command creates the final program, which will run faster.

My question is, why is that when I do cargo build --release, it compiles the code, which is fine. But when I execute cargo run, it again compiles the code, even though I haven't changed any code since. It is working normally with cargo build, followed by cargo run i.e compiling one time with the former command.

naufil@naufil-Inspiron-7559:~/Desktop/rust/20April/variables$ cargo build
   Compiling variables v0.1.0 (/home/naufil/Desktop/rust/20April/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.35s
naufil@naufil-Inspiron-7559:~/Desktop/rust/20April/variables$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `target/debug/variables`
Hello, world! 6
naufil@naufil-Inspiron-7559:~/Desktop/rust/20April/variables$ cargo build --release
   Compiling variables v0.1.0 (/home/naufil/Desktop/rust/20April/variables)
    Finished release [optimized] target(s) in 0.34s
naufil@naufil-Inspiron-7559:~/Desktop/rust/20April/variables$ cargo run
   Compiling variables v0.1.0 (/home/naufil/Desktop/rust/20April/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.23s
     Running `target/debug/variables`
Hello, world! 6
Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
Muhammad Naufil
  • 2,420
  • 2
  • 17
  • 48

1 Answers1

15

cargo run attempts to run the debug build of your project. Use cargo run --release instead. A cargo build --release followed by cargo run --release won't compile again.

Cargo maintains two pretty much completely independent sets of build artifacts:

  • The debug build, stored in target/debug/
  • The release build, stored in target/release/

All of these sub-commands allow you to specify which of these profiles to use (not necessarily an exhaustive list):

  • Default: debug (switch to release mode with --release)
    • cargo build
    • cargo run
    • cargo test
    • cargo check
  • Default: release (switch to debug mode with --debug)
    • cargo bench
    • cargo install
Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305