28

I put this in my Cargo.toml

[build]
target-dir = "../my-target"

However, Cargo doesn't recognize this key.

cargo run --release --bin my_project

warning: unused manifest key: build
error: failed to open: /.../project-root/target/releases/.cargo-lock

Caused by:
  Permission denied (os error 13)

The custom target dir with the environment variable works:

CARGO_TARGET_DIR=../my-target cargo run --bin my_project

but how can I specify '../my-target' in Cargo.toml?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
mq7
  • 1,125
  • 2
  • 11
  • 21

3 Answers3

27

Use the CARGO_TARGET_DIR environment variable:

CARGO_TARGET_DIR=../my-target cargo run --bin my_project

(This is stated in the question, but I wanted to highlight it for anyone that skips over that)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • This works very well in `Makefile` if you specify some `RUSTFLAGS` value there, since changing `RUSTFLAGS` value invalidates the compiled cache -- unless it's stored in a separate folder. – Thorkil Værge Jul 05 '23 at 11:28
26

[build] is a Cargo-level configuration rather than for the project:

This document will explain how Cargo’s configuration system works, as well as available keys or configuration. For configuration of a project through its manifest, see the manifest format.

Put your [build] inside $PROJECT_DIR/.cargo/config.toml or even $HOME/.cargo/config.toml. See the above link for all the options.

mike rodent
  • 14,126
  • 11
  • 103
  • 157
sdht0
  • 500
  • 4
  • 8
2

Besides setting the CARGO_TARGET_DIR environment variable or the build.target-dir setting in /.cargo/config.toml, Cargo also has the --target-dir CLI option for specifying the target directory.

Jonathan Feenstra
  • 2,534
  • 1
  • 15
  • 22