dtolnay/cxx

cxx::bridge behind a feature

Aperta

#1325 aperta il 12 mar 2024

 (2 commenti) (5 reazioni) (0 assegnatari)Rust (253 fork)batch import
help wanted

Metriche repository

Star
 (4472 stelle)
Metriche merge PR
 (Merge medio 8m) (3 PR mergiate in 30 g)

Descrizione

I would like to conditionally compile some code only when C++ is also compiled. This is for testing purpose, the tests need some data from the module ffi but not everything inside there, just a few struct.

#[cxx::bridge(namespace = "ao::rust")]
mod ffi {
    pub struct Uuid { // like this one
        pub a: u64,
        pub b: u64,
    }
    #[cfg(feature = "cpp")]
    extern "Rust" {
        // ... not needed, only if compiling c++
    }
}

The problem is when I run the tests from the VS Code UI, It will give an error:

error[E0433]: failed to resolve: use of undeclared crate or module `cxx`
  --> rust_pricing/src/lib.rs:77:3
   |
77 | #[cxx::bridge(namespace = "ao::rust")]
   |   ^^^ use of undeclared crate or module `cxx`

In order t fix the error I put the bridge behind a features like this:

#[cfg_attr(feature = "cpp", cxx::bridge(namespace = "ao::rust"))]
mod ffi {
}

Now running tests from UI works but compiling rust from C++ does not work anymore, I get the error:

[build] error: failed to run custom build command for `rust_pricing v0.1.0 .../ao_rust_sources/rust_pricing)`
[build] 
[build] Caused by:
[build]   process didn't exit successfully: `.../ao_rust_sources/target/release/build/rust_pricing-779c278cdc2546c4/build-script-build` (exit status: 1)
[build]   --- stderr
[build]   cxxbridge: no #[cxx::bridge] module found in src/lib.rs

Apparently it expects exactly #[cxx::bridge(namespace = "ao::rust")], not cfg_attr Is there a way to fix both?

Guida contributor