How do I generate a text file during compile time and include its content in the output?

混江龙づ霸主 提交于 2020-01-05 11:49:54

问题


I'm trying to do almost the same as How to create a static string at compile time.

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);
}

Upon cargo build I'm getting the error:

error: couldn't read src\file_path.txt: The system cannot find the file specified. (os error 2)
 --> src\main.rs:3:40
  |
3 |     static LONG_STRING: &'static str = include_str!("file_path.txt");
  |                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I can see that the file is generated at

X:\source\github\rust-build-script-example\target\debug\build\rust-build-script-example-f2a03ef7abfd6b23\out\file_path.txt
  1. What is the environment variable I have to use instead of OUT_DIR in order to get the file_path.txt to be output to the src directory?
  2. If #1 is not possible, then how do I include_str! the generated file in the above directory without hardcoding it in code (since the path seems to have a randomly generated partial rust-build-script-example-f2a03ef7abfd6b23 in it)

My GitHub repository


回答1:


The trick was

concat!(env!("OUT_DIR"), "/file_path.txt")

I changed my main.rs as follows and it worked.

fn main() {

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

    println!("{}", LONG_STRING);
}

The following crates.io documentation helped

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




回答2:


If anyone is interested in a more convenient way to achieve the same, I also created the build_script_file_gen crate which can be used as follows

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"));
}


来源:https://stackoverflow.com/questions/47217283/how-do-i-generate-a-text-file-during-compile-time-and-include-its-content-in-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!