如何在编译期间生成文本文件并将其内容包含在输出中?

Har*_*aka 6 build build-script embedded-resource rust rust-cargo

我正在尝试执行与如何在编译时创建静态字符串几乎相同的操作

构建.rs

use std::{env};
use std::path::Path;
use std::io::{Write, BufWriter};
use std::fs::File;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("file_path.txt");
    let mut f = BufWriter::new(File::create(&dest_path).unwrap());

    let long_string = dest_path.display();
    write!(f, "{}", long_string).unwrap();
}
Run Code Online (Sandbox Code Playgroud)

主文件

fn main() {

    static LONG_STRING: &'static str = include_str!("file_path.txt");
    println!("{}", LONG_STRING);
}
Run Code Online (Sandbox Code Playgroud)

cargo build我收到错误时:

use std::{env};
use std::path::Path;
use std::io::{Write, BufWriter};
use std::fs::File;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("file_path.txt");
    let mut f = BufWriter::new(File::create(&dest_path).unwrap());

    let long_string = dest_path.display();
    write!(f, "{}", long_string).unwrap();
}
Run Code Online (Sandbox Code Playgroud)

我可以看到文件是在

fn main() {

    static LONG_STRING: &'static str = include_str!("file_path.txt");
    println!("{}", LONG_STRING);
}
Run Code Online (Sandbox Code Playgroud)
  1. 为了file_path.txt将要输出到src目录,我必须使用什么环境变量而不是 OUT_DIR ?
  2. 如果#1 是不可能的,那么我如何include_str!在上面的目录中生成文件而不用代码对其进行硬编码(因为路径中似乎有一个随机生成的部分rust-build-script-example-f2a03ef7abfd6b23

我的 GitHub 存储库

Har*_*aka 10

诀窍是

concat!(env!("OUT_DIR"), "/file_path.txt")
Run Code Online (Sandbox Code Playgroud)

我按如下方式更改了我的 main.rs 并且它起作用了。

fn main() {

    static LONG_STRING: &'static str = include_str!(concat!(env!("OUT_DIR"), "/file_path.txt"));

    println!("{}", LONG_STRING);
}
Run Code Online (Sandbox Code Playgroud)

以下 crates.io 文档有帮助

http://doc.crates.io/build-script.html

https://doc.rust-lang.org/cargo/reference/environment-variables.html