You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何条件性包含Rust示例,或仅针对特定平台编译示例?

如何条件性地包含Cargo的[[example]]?

我有一个仅能在类Unix系统运行的示例,在Windows平台编译或运行会报错。我希望避免在main.rs的每一个顶层项上添加#[cfg(not(target_family = "windows"))],同时不想破坏现有代码结构(比如引入额外模块),也不想影响IDE的代码辅助功能。

已尝试的无效方案

  • 将Cargo.toml中的[[example]]改为[[target.'cfg(not(target_family = "windows"))'.example]],此写法无效。
  • 在示例文件顶部添加#![cfg(not(target_family = "windows"))],会触发错误:main function not found in crate my_example。
  • 添加#![cfg_attr(target_family = "windows", crate_type = "lib")],但该属性已被弃用,报错:crate_type within an #![cfg_attr] attribute is deprecated。
  • 尝试使用声明式宏包裹代码,但宏无法匹配mod项,且会影响IDE辅助功能,宏代码如下:
macro_rules! no_windows {
    (
        $( x:item )*
    ) => {
        $( 
            #[cfg(not(target_family = "windows"))]
            $x
        )*

        #[cfg(target_family = "windows")]
        fn main() {
            unimplemented!();
        }
    };
}

no_windows! {

// normal code here

}

可行解决方案

方案1:使用Cargo.toml的目标条件配置(推荐)

直接修改[[example]]的条件写法无效,但可以通过在Cargo.toml中针对非Windows平台单独声明示例:

[target.'cfg(not(target_family = "windows"))'.examples]
unix_only = { path = "examples/unix_only.rs" }

这种写法会让Cargo仅在非Windows平台识别该示例,Windows下不会尝试编译它,完全符合需求,且不影响代码结构和IDE集成。

方案2:给示例文件添加cfg属性并补充空main

在示例的main.rs顶部添加以下代码:

#![cfg_attr(target_family = "windows", allow(unused))]

#[cfg(not(target_family = "windows"))]
fn main() {
    // 原有的类Unix平台业务代码
}

#[cfg(target_family = "windows")]
fn main() {
    // 输出提示或空实现
    eprintln!("该示例仅支持类Unix系统");
}

这种方式不需要修改Cargo.toml,Windows下会编译一个仅输出提示的main函数,避免编译报错,同时原代码无需拆分模块,IDE也能正常识别所有代码内容。

内容的提问来源于stack exchange,提问作者Mingwei Samuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:02:40