是否可以检查您的系统上是否在 Rust 中定义了 C 宏? [英] Is it possible to check whether a C macro is defined on your system in Rust?

查看:71
本文介绍了是否可以检查您的系统上是否在 Rust 中定义了 C 宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Rust 中的 libc crate 包含许多用于 Rust 的 C 标准宏和函数,但它也声明它不关心系统之间的可移植性.我正在将一些大量使用 C 的预处理器宏的代码从 C 移植到 Rust,并且仅在定义了给定宏的情况下才包含一些代码:在本例中为 O_BINARY.是否可以检查 O_BINARY 宏是否在我的系统上用 Rust 定义,如果是,它看起来像什么?

I'm aware that the libc crate in Rust contains much of C's standard macros and functions for use in Rust, but it also states that it is not concerned with portability between systems. I'm porting some code that uses C's preprocessor macros extremely heavily from C to Rust, and only includes some code if a given macro is defined: in this case O_BINARY. Is it possible to check whether the O_BINARY macro is defined on my system in Rust, and if so, what does this look like?

我正在寻找一种可以相当接近地复制此 C 语法的构造:

I'm looking for a construct that can replicate this C syntax rather closely:

#ifdef O_BINARY
// Some extra code here
#endif
// Regular code

推荐答案

您可以在构建脚本中运行 C 预处理器并检查输出.如果定义了宏,我们就可以将功能标志传递给 Rust 代码.

You can run the C preprocessor in a build script and inspect the output. If the macro is defined, we can then pass along a feature flag to the Rust code.

Cargo.toml

[build-dependencies]
cc = "1.0.37"

build.rs

fn main() {
    let check = cc::Build::new().file("src/o_binary_check.c").expand();
    let check = String::from_utf8(check).unwrap();
    if check.contains("I_HAVE_O_BINARY_TRUE") {
        println!("rustc-cfg=o_binary_available");
    }
}

src/o_binary_check.c

#ifdef O_BINARY
I_HAVE_O_BINARY_TRUE
#else
I_HAVE_O_BINARY_FALSE
#endif

根据需要调整此文件以找到您的宏.

Tweak this file as appropriate to find your macros.

src/main.rs

fn main() {
    if cfg!(feature = "o_binary_available") {
        println!("O_BINARY is available");
    } else {
        println!("O_BINARY is not available");
    }
}

另见:

这篇关于是否可以检查您的系统上是否在 Rust 中定义了 C 宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆