dtolnay/cxx

cxx::bridge behind a feature

Open

#1,325 opened on Mar 12, 2024

View on GitHub
 (2 comments) (5 reactions) (0 assignees)Rust (253 forks)batch import
help wanted

Repository metrics

Stars
 (4,472 stars)
PR merge metrics
 (Avg merge 8m) (3 merged PRs in 30d)

Description

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?

Contributor guide