DAILY DOCDAILY DOC
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
  • rust

    • Rust
    • add
    • 属性(attributes)
    • cargo issue
    • cli
    • build.rs
    • Enums
    • eventEmitter(rust)
    • 格式化输出 std::fmt
    • rust iterator
    • rust 学习计划
    • 生命周期(lifetime)
    • Linked List
    • log
    • macros
    • mem::size_of
    • niche optimization
    • Rust 所有权
    • 模式匹配(pattern matching)
    • module system
    • result & option
    • .rust-analyzer.json
    • rust startup
    • rust-test
    • 可见性(visibility)
    • cargo
    • toml

build.rs

A build.rs script in a Rust project is used to perform custom build steps before the main compilation. These steps might include generating code, compiling other languages, or setting environment variables. The output from build.rs can sometimes be confusing if it doesn't show up as expected. Here’s how to properly write and debug a build.rs file.

Example of a Basic build.rs File

Here’s a simple example of a build.rs file that prints messages and sets environment variables:

use std::env;
use std::fs::File;
use std::io::Write;

fn main() {
    // Print messages to the build output
    println!("Hello from build.rs!");

    // Print a cargo directive to rerun the build script if build.rs changes
    println!("cargo:rerun-if-changed=build.rs");

    // Print a cargo directive to set an environment variable
    println!("cargo:rustc-env=MY_ENV_VAR=Hello from build.rs!");

    // Write to a file for debugging purposes
    let mut file = File::create("build_output.txt").expect("Could not create file");
    writeln!(file, "Hello from build.rs!").expect("Could not write to file");

    // Example of setting an environment variable for the Rust compiler
    env::set_var("MY_BUILD_VAR", "Some value");
}
Last Updated:
Contributors: rosendo
Prev
cli
Next
Enums