Open In App

Rust – Build Scripts

Improve
Improve
Like Article
Like
Save
Share
Report

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

 

In the main.rs file, the code is:

Rust




include!(concat!(env!("OUT_DIR"), "/gfg.rs"));
  
fn main() {
    println!("Printing: {}", message());
}


In the build.rs, the code is:

Rust




use std::env;
use std::fs;
use std::path::Path;
  
fn main() {
    let out_dir = env::var_os("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("gfg.rs");
    fs::write(
        &dest_path,
        "pub fn message() -> &'static str {
            \"Geeks for Geeks!\"
        }
        "
    ).unwrap();
    println!("cargo:rerun-if-changed=build.rs");
}


Output:

For getting the output, we put cargo run

 

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.



Last Updated : 29 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads