Get the name and path of the binary being build in the build script

I am compiling an application for an embedded platform.
During the build I would like to generate some files that are needed to load the application on the device.
For generating these files I need the name and path to the final binary that is being build.

My crate contains a main binary and multiples examples which needs these configuration files.
When I build the main binary with cargo build
I would like to create a file like this:

{
   "application": {
        "name": "app",
        "path": "target/thumbv7/debug/app",
        ...
}

While when I build the examples with `cargo build --example example_1'
I would like to create these kind of files:

{
   "application": {
        "name": "example_1",
        "path": "target/thumbv7/debug/example/example_1",
        ...
}

I did not find this information as part of the environment variables passed to the build script.
Is there a way to get this in the build script.

I know cargo will set the $CARGO_BIN_EXE_foo environment variable when building the foo binary's integration tests or benchmarks, but I don't think that's available before the binary is compiled (i.e. from a build script).

Alternatively, you can use the cargo metadata command (and the cargo_metadata::Metadata wrapper) to find out things like your library's name and the target directory.

You could combine that with the cargo xtask pattern to create a cargo xtask dist command that generates your JSON file and does any other packaging work.

If your binary needs to use the generated file, one thing you could use is the "self modifying" code trick by the same author to generate the file and keep it in sync.

Thanks,
I will try to create a cargo subcommand with cargo_metadata to generate my test config files.
If that works I may integrate it in a xtasks.

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.