我正在尝试执行与如何在编译时创建静态字符串几乎相同的操作。
build.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();
}
main.rs
fn main() {
static LONG_STRING: &'static str = include_str!("file_path.txt");
println!("{}", LONG_STRING);
}
cargo build
时,我收到错误:
error: couldn't read srcfile_path.txt: The system cannot find the file specified. (os error 2)
--> srcmain.rs:3:40
|
3 | static LONG_STRING: &'static str = include_str!("file_path.txt");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我可以看到该文件是在
X:sourcegithubrust-build-script-exampletargetdebugbuildrust-build-script-example-f2a03ef7abfd6b23outfile_path.txt
- 为了将
file_path.txt
输出到src
目录,我必须使用什么环境变量而不是OUT_DIR? - 如果 #1 是不可能的,那么我如何在上面目录中
include_str!
生成的文件而不在代码中硬编码(因为路径中似乎有一个随机生成的部分rust-build-script-example-f2a03ef7abfd6b23
(
我的 GitHub 存储库
诀
窍是
concat!(env!("OUT_DIR"), "/file_path.txt")
我按如下方式更改了 main.rs,它奏效了。
fn main() {
static LONG_STRING: &'static str = include_str!(concat!(env!("OUT_DIR"), "/file_path.txt"));
println!("{}", LONG_STRING);
}
以下 crates.io 文档有所帮助
http://doc.crates.io/build-script.html
https://doc.rust-lang.org/cargo/reference/environment-variables.html
如果有人对更方便的方法感兴趣,我还创建了build_script_file_gen箱,可以按如下方式使用
build.rs
extern crate build_script_file_gen;
use build_script_file_gen::gen_file_str;
fn main() {
let file_content = "Hello World!";
gen_file_str("hello.txt", &file_content);
}
main.rs
#[macro_use]
extern crate build_script_file_gen;
fn main() {
println!(include_file_str!("hello.txt"));
}