Har*_*aka 6 build build-script embedded-resource rust rust-cargo
我正在尝试执行与如何在编译时创建静态字符串几乎相同的操作。
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)
file_path.txt
将要输出到src
目录,我必须使用什么环境变量而不是 OUT_DIR ?include_str!
在上面的目录中生成文件而不用代码对其进行硬编码(因为路径中似乎有一个随机生成的部分rust-build-script-example-f2a03ef7abfd6b23
)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