crossbundle_tools/commands/android/common/rust_compile/
cmake_toolchain.rs

1use crate::types::*;
2use std::io::Write;
3
4/// Sets needed environment variables
5pub fn set_cmake_vars(
6    build_target: crate::types::AndroidTarget,
7    ndk: &AndroidNdk,
8    target_sdk_version: u32,
9    build_target_dir: &std::path::Path,
10) -> cargo::CargoResult<()> {
11    // Return path to toolchain cmake file
12    let cmake_toolchain_path = write_cmake_toolchain(
13        target_sdk_version,
14        ndk.ndk_path(),
15        build_target_dir,
16        build_target,
17    )?;
18
19    // Set cmake environment variables
20    std::env::set_var("CMAKE_TOOLCHAIN_FILE", cmake_toolchain_path);
21    std::env::set_var("CMAKE_GENERATOR", r#"Unix Makefiles"#);
22    std::env::set_var("CMAKE_MAKE_PROGRAM", make_path(ndk.ndk_path()));
23    Ok(())
24}
25
26/// Returns path to NDK provided make
27pub fn make_path(ndk_path: &std::path::Path) -> std::path::PathBuf {
28    ndk_path
29        .join("prebuild")
30        .join(super::consts::HOST_TAG)
31        .join("make")
32}
33
34/// Write a CMake toolchain which will remove references to the rustc build target before
35/// including the NDK provided toolchain. The NDK provided android toolchain will set the
36/// target appropriately Returns the path to the generated toolchain file
37pub fn write_cmake_toolchain(
38    min_sdk_version: u32,
39    ndk_path: &std::path::Path,
40    build_target_dir: &std::path::Path,
41    build_target: crate::types::AndroidTarget,
42) -> cargo::util::CargoResult<std::path::PathBuf> {
43    let toolchain_path = build_target_dir.join("cargo-apk.toolchain.cmake");
44    let mut toolchain_file = std::fs::File::create(&toolchain_path).unwrap();
45    writeln!(
46        toolchain_file,
47        r#"set(ANDROID_PLATFORM android-{min_sdk_version})
48        set(ANDROID_ABI {abi})
49        string(REPLACE "--target={build_target}" "" CMAKE_C_FLAGS "${{CMAKE_C_FLAGS}}")
50        string(REPLACE "--target={build_target}" "" CMAKE_CXX_FLAGS "${{CMAKE_CXX_FLAGS}}")
51        unset(CMAKE_C_COMPILER CACHE)
52        unset(CMAKE_CXX_COMPILER CACHE)
53        include("{ndk_path}/build/cmake/android.toolchain.cmake")"#,
54        min_sdk_version = min_sdk_version,
55        ndk_path = dunce::simplified(ndk_path).to_string_lossy(),
56        build_target = build_target.rust_triple(),
57        abi = build_target.android_abi(),
58    )?;
59    Ok(toolchain_path)
60}