diff --git a/src/bindgen/cargo/cargo_expand.rs b/src/bindgen/cargo/cargo_expand.rs index 997097711..679f6cd81 100644 --- a/src/bindgen/cargo/cargo_expand.rs +++ b/src/bindgen/cargo/cargo_expand.rs @@ -83,6 +83,10 @@ pub fn expand( cmd.env("CARGO_TARGET_DIR", PathBuf::from(path).join("expanded")); } + // Set this variable so that we don't call it recursively if we expand a crate that is using + // cbindgen + cmd.env("_CBINDGEN_IS_RUNNING", "1"); + cmd.arg("rustc"); cmd.arg("--lib"); cmd.arg("--manifest-path"); diff --git a/src/bindgen/parser.rs b/src/bindgen/parser.rs index a7cd618fd..bfa4c2167 100644 --- a/src/bindgen/parser.rs +++ b/src/bindgen/parser.rs @@ -179,6 +179,13 @@ impl<'a> Parser<'a> { fn parse_expand_crate(&mut self, pkg: &PackageRef) -> Result<(), Error> { assert!(self.lib.is_some()); + // If you want to expand the crate you run cbindgen on you might end up in an endless + // recursion if the cbindgen generation is triggered from build.rs. Hence don't run the + // expansion if the build was already triggered by cbindgen. + if std::env::var("_CBINDGEN_IS_RUNNING").is_ok() { + return Ok(()); + } + let mod_parsed = { if !self.cache_expanded_crate.contains_key(&pkg.name) { let s = self