Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force `build.rs` to run again without cleaning my whole project?

How can I force build.rs to run again without cleaning my whole project? I checked cargo build --help but I couldn't find anything related to build.rs.

like image 346
tversteeg Avatar asked Mar 02 '18 20:03

tversteeg


People also ask

Where do I put build RS files?

Placing a file named build.rs in the root of a package will cause Cargo to compile that script and execute it just before building the package. Some example use cases of build scripts are: Building a bundled C library.

What is build script build EXE?

A build script is a file that is started by a build plan. The build script prepares output from generated files.

What is cargo build?

Cargo is Rust's build system and package manager. Most Rustaceans use this tool to manage their Rust projects because Cargo handles a lot of tasks for you, such as building your code, downloading the libraries your code depends on, and building those libraries.


2 Answers

If build.rs changes, Cargo already rebuilds the project:

Note that if the build script itself (or one of its dependencies) changes, then it's rebuilt and rerun unconditionally, so cargo:rerun-if-changed=build.rs is almost always redundant (unless you want to ignore changes in all other files except for build.rs). doc

On Linux, I will just do touch build.rs && cargo build. For Windows, see Windows equivalent of the Linux command 'touch'?

like image 121
Stargateur Avatar answered Sep 28 '22 00:09

Stargateur


Register build.rs as a crate's bin target:

  1. Add this to your Cargo.toml file:

    [package]
    edition = "2018"
    build = "build.rs"
    
    [[bin]]
    name = "force-build"
    path = "build.rs"
    required-features = ["build_deps"]  # only needed for build-dependencies
    
  2. If you have any [build-dependencies] (e.g. some_crate = "1.2.3"), you need to add those to (the main) [dependencies] (sadly no [bin-dependencies] as of yet), but you can make them optional:

    [dependencies]
    some_crate = { version = "1.2.3", optional = true }
    
    [features]
    build_deps = ["some_crate"]
    

Then you can run the build script with:

$ cargo run --bin force-build --features build_deps

(or $ cargo run --bin force-build when no [build-dependencies])

  • You can even disable the automatic call of the build script by replacing the build = "build.rs" line in Cargo.toml with build = false

  • Note: since the OUT_DIR env var is not present for bin targets, if your build.rs script uses env!("OUT_DIR"), you may "fix this" by using concat!(env!("CARGO_MANIFEST_DIR"), "/target/") instead.

like image 35
Daniel H-M Avatar answered Sep 28 '22 01:09

Daniel H-M