Is it possible to check whether a C macro is defined on your system in Rust?

天涯浪子 提交于 2020-05-26 09:14:22

问题


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?

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

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

回答1:


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

See also:

  • How do I use C preprocessor macros with Rust's FFI?
  • Build Scripts in The Cargo Book


来源:https://stackoverflow.com/questions/56926798/is-it-possible-to-check-whether-a-c-macro-is-defined-on-your-system-in-rust

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