Skip to content

Commit ec98342

Browse files
committed
fix: set CMAKE_ANDROID_NDK for Android cross-compilation
cmake-rs sets CMAKE_SYSTEM_NAME=Android but not CMAKE_ANDROID_NDK, causing CMake >= 3.21 to fail with 'Neither the NDK or a standalone toolchain was found'. Detect NDK root from environment variables and pass it to cmake::Config.
1 parent 0bf93a1 commit ec98342

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

build.rs

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,40 @@
11
use std::env;
22
use std::path::PathBuf;
33

4+
/// When cross-compiling for Android, the `cmake` crate (cmake-rs) sets
5+
/// `CMAKE_SYSTEM_NAME=Android` but does **not** set `CMAKE_ANDROID_NDK`.
6+
/// CMake ≥ 3.21's `Platform/Android-Determine.cmake` then fails because it
7+
/// cannot locate the NDK.
8+
///
9+
/// This function detects the Android NDK root from well-known environment
10+
/// variables (the same ones CMake itself checks).
11+
fn detect_android_ndk() -> Option<PathBuf> {
12+
for var in ["ANDROID_NDK_ROOT", "ANDROID_NDK_HOME", "ANDROID_NDK"] {
13+
if let Ok(val) = env::var(var) {
14+
let p = PathBuf::from(&val);
15+
if p.is_dir() {
16+
return Some(p);
17+
}
18+
}
19+
}
20+
None
21+
}
22+
423
fn main() {
24+
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
25+
526
// Build libversion static library using cmake
6-
let dst = cmake::Config::new("libversion")
7-
.build_target("libversion_static")
8-
.build();
27+
let mut cmake_cfg = cmake::Config::new("libversion");
28+
cmake_cfg.build_target("libversion_static");
29+
30+
// Work around cmake-rs not setting CMAKE_ANDROID_NDK for Android targets.
31+
if target_os == "android" {
32+
if let Some(ndk_root) = detect_android_ndk() {
33+
cmake_cfg.define("CMAKE_ANDROID_NDK", &ndk_root);
34+
}
35+
}
36+
37+
let dst = cmake_cfg.build();
938

1039
let build_dir = dst.join("build").join("libversion");
1140
println!("cargo:rustc-link-search=native={}", build_dir.display());

0 commit comments

Comments
 (0)