如果标志包含 space,我如何从构建脚本将标志传递给 rustc?

How can I pass flags to rustc from a build script if they contain a space?

我正在编写一个带有一些 C 集成的 Rust 程序,所以我使用的是自定义构建脚本。在此脚本中,我将 -L <path to library> 传递给 rustc,但这仅在 <path to library> 不包含 space 时有效。 build.rs 中的确切行:

println!(r"cargo:rustc-flags= -L {}/target/sdsl/sdsl_install/lib -l sdsl -l divsufsort -l divsufsort64 -l stdc++", current_dir);

如果 current_dir 包含 space 我会得到这个错误

error: Only `-l` and `-L` flags are allowed in build script of `top_tree_compression v0.1.0 (file:///home/jan/Uni/Bachelorarbeit/Programme/Top_Tree%20Compression)`: `-L /home/jan/Uni/Bachelorarbeit/Programme/Top_Tree Compression/target/sdsl/sdsl_install/lib -l sdsl -l divsufsort -l divsufsort64 -l stdc++`

我试图在 space 之前写一个 \ 来转义它,但它给了我同样的错误。然后我尝试用 %20 替换 space 因为在错误消息中 space 被替换为这个,但是由于路径不正确我得到一个链接错误。

看来你不能从 Rust 1.29 开始。 source code for the current master of Cargo:

let mut flags_iter = value
    .split(|c: char| c.is_whitespace())
    .filter(|w| w.chars().any(|c| !c.is_whitespace()));

这天真地在任何空格上拆分参数,无论它出现在哪里。这似乎是 Cargo 的一个错误或限制,您应该寻找一个已经提交的问题或自己提交一个问题。


话虽如此,如果您使用更适合用途的 rustc-link-librustc-link-search 参数,空格就可以正常工作:

println!(r#"cargo:rustc-link-search={}/target/sdsl/sdsl_install/lib"#, "some thing");
$ cargo run --verbose
   Compiling xx v0.1.0 (file:///private/tmp/xx)
     [...snip...]
     Running `rustc [...snip...] -L 'some thing/target/sdsl/sdsl_install/lib'`