Customise the target location of cargo build

TLDR: specify directory of where output binary goes.

I have a project structured in the format below (if it's not proper, advice is welcome). The top level crate (or package, not sure how it should be called) is a workspace with 2 members, the generated and generator crate. The generator crate generates rust files and saves them in generated_crate/src/bin/.

I have a script in generated_crate that calls cargo run iteratively on all the generated files but I'd rather compile and build all the binaries and put them in some folder that I specify inside the generated crate, where I can run them all at once. In the future I'll be compiling the generated files with different opt flags, which is why I want to be able to specify the build location.

Currently when I run cargo build from inside the generated crate, it generates to the target directory located at the top level workspace (see in the tree below).

├── Cargo.lock
├── Cargo.toml
├── generated crate
│   ├── Cargo.toml
│   ├──
│   └── src
│       ├── bin (generated .rs files which I want to build into binaries)
│       ├──
│       └──
├── generator crate
│   ├── Cargo.toml
│   └── src
│       ├──
│       └──
├── target <-- binaries from cargo build from generated goes here
└── src

The cargo build command has an --out-dir argument which is where it'll copy compiled artifacts. You also have the --target-dir argument (or CARGO_TARGET_DIR environment variable), but you've already mentioned you don't want to add logic that changes based on release/debug.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.