Cargo OUT_DIR question

I'm generating shell completions and png icons in my build.rs currently. My question revolves around how Cargo decides what the var OUT_DIR is going to resolve to, because I would like to automate packaging as much as possible. It's always target/<profile>/build/<crate-name>-<hash>/out. What I don't know is how the hash is derived or whether it's at all predictable. If not, I suppose I could always just capture the cargo terminal output.

The $OUTDIR directory is only meant for things that are needed to build the main crate (e.g. generated code or native libraries you need to link to) and you shouldn't be trying to access it outside of a build.

If you just need those files to be accessible at runtime, you could use the include_str!() and include_bytes!() macros to embed them in your final executable.

// lib.rs

const BASH_COMPLETIONS: &str = include_str!(concat!(env!("OUT_DIR"), "/bash.inc"));
const ICON: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/icon.png"));

However, if you are wanting to automate the entire build+package process, I would use the cargo xtask pattern and make a cargo xtask dist command that compiles your main application, generates completions and icons, then packages them up.

3 Likes

That looks like a nice solution actually. I wasn't aware of it previously.

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.