生成文件
Cargo.toml
[package]build = "build.rs"
build.rs
use std::env;use std::fs::File;use std::io::Write;use std::path::Path;fn main() {let out_dir = env::var("OUT_DIR").unwrap();let dest_path = Path::new(&out_dir).join("hello.rs");let mut f = File::create(&dest_path).unwrap();f.write_all(b"fn say_hello() -> &'static str {\"hello\"}",).unwrap();}
执行文件:
// 构建脚本// 指定的 build 命令,将在包编译之前,被编译和调用,从而具备 rust 代码所依赖// 构建一个捆绑的 C 库;// 在主机系统上找到 C 库;// 生成 Rust 模块;// 为 crate 执行所需某平台的特定配置;// [package]// cargo.toml 添加 build = "build.rs"include!(concat!(env!("OUT_DIR"), "/hello.rs"));fn main() {println!("{}", say_hello());}
编译 C 文件
[package]build = "build.rs"[build-dependencies]cc = "1.0"
build.rs
extern crate cc;fn main() {cc::Build::new().file("src/hello.c").compile("hello");}
执行文件:
extern "C" {fn hello();}fn main() {// invoke the c functionunsafe {hello();}}
