How to check crate type in rust code?

I want my code run some extra codes if the code is built as a dylib, I wrote something like this:

#[no_mangle]
extern "C" fn print_target2() -> String {
    if cfg!(crate_type = "cdylib") {
        println!("it works")
    }
}

or like this:

#[cfg(crate_type = "cdylib")]
#[no_mangle]
extern "C" fn print_target2() -> String {
    println!("it works")
}

but it doesn't work. Any idea how I can do this?

This old issue seems to indicate that cfg(crate_type) is desired but not implemented. I don't know whether there's a good workaround, I though about whether you could do it with build.rs to emit a custom cargo:rustc-cfg, but couldn't figure out how you would extract the crate_type from the available environment variables.

according to your link, I think it may not implemented for a reason, maybe because crate-type = ["rlib","cdylib"] is passed together to rustc once, not separately to build two lib one by one, so the checking may apply both for rlib and cdylib...

I'm considering adding a custom feature instead of checking crate-type now...

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.