Binary directory about 'cargo build' and 'cargo build --target x86_64-unknown-linux-gnu' under linux

Perform the following two compilations under Linux:

  • cargo build will place binary with directory "target/debug"
  • cargo build --target x86_64-unknown-linux-gnu will place binary with directory "target/x86_64-unknown-linux-gnu/debug"

But in build.rs script, the env of "TARGET" is the same, So are there any other ways to known where the binary file was placed?

what do you want to do in your build script? cargo build scripts are not supposed to inspect the crates' build artifacts, because build scripts run before the crates are compiled. if build scripts want to generate some artifacts for the rust code, it should use OUT_DIR.

TKS, Yes. Build script genenrates or downloads some resources, such as images, jsons. The crates build binary artifacts depends on these resources to run.
If I want to enable some unstable features by pass -Z build-std=std, it requires to pass --target config, thus the build script has no idea about the crates' binary artifacts placed.

you should put these files under the directory specified by the environment variable OUT_DIR, which is set by cargo specifically for this purpose.

// build.rs
fn main() {
    let out_dir: PathBuf = std::env::var_os("OUT_DIR").unwrap().into();
    std::fs::write(out_dir.join("data.json"), some_json_data).expect("write data.json");
}
1 Like

If those artifacts are needed at compile time (because they will be compiled into the final binary) then as @nerditation said they should go into OUT_DIR.

If they are required at runtime you will need some external tooling to bundle it up anyway, because cargo is not good at that (e.g. cargo install will build a crate and copy that binary into ~/.cargo/bin and only the binary, additional resources are not considered).

1 Like

Unfortunately, Cargo doesn't tell the exact path to produced binaries.

In tests there is CARGO_BIN_EXE_<name of binary> env var that you can use to run binaries built in target/.

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.