VOOZH about

URL: https://www.geeksforgeeks.org/rust/rust-build-scripts/

⇱ Rust - Build Scripts - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rust - Build Scripts

Last Updated : 28 Apr, 2025

In Rust, there is an option for building scripts where Cargo compiles a built script into an executable file, and after running the script, many tasks can be performed. There are scenarios where we need different options for generating a code before it's built. The cargo compiler in this case compiles the script and integrates it with build scripts.

To execute this step, we need to declare a build.rs file in the root directory.

Example:

In this example, we declare a file build.rs

👁 Image

In the main.rs file, the code is:

In the build.rs, the code is:

Output:

For getting the output, we put cargo run

👁 Image

Explanation:

In the main.rs file, we have declared an expression include! concat! and env! which means that the library build.rs is defined in the rust module and once we use the concat! macro and the env! macro the gfg.rs file is generated for the rust crate to compile.

In the build.rs file, the Out_dir envt variable is declared for knowing the location of the output files. Also, the rerun-if-changed instruction tells cargo that the scripts would be re-run in case the build script is changed and this line ensures that cargo automatically runs if any build script changes with a change in the package.

Comment