Skip to content

Instantly share code, notes, and snippets.

@mamcx
Created October 9, 2025 15:03
Show Gist options
  • Select an option

  • Save mamcx/8ed041ce84c0b75afd07a70934bfabc6 to your computer and use it in GitHub Desktop.

Select an option

Save mamcx/8ed041ce84c0b75afd07a70934bfabc6 to your computer and use it in GitHub Desktop.
Build file to cross-compile to android
use std::env;
/// Standard library path inside NDK directory.
const LINUX_X86_64_LIB_DIR: &str =
"/toolchains/llvm/prebuilt/linux-x86_64/lib64/clang/14.0.7/lib/linux/";
const MACOS_X86_64_LIB_DIR: &str =
"/toolchains/llvm/prebuilt/darwin-x86_64/lib64/clang/14.0.7/lib/linux";
fn main() {
let target_os = env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS not set");
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH not set");
if target_os == "android" {
let android_ndk = env::var("ANDROID_NDK_HOME").expect("ANDROID_NDK_HOME not set");
let lib_dir = match env::consts::OS {
"linux" => LINUX_X86_64_LIB_DIR,
"macos" => MACOS_X86_64_LIB_DIR,
_ => panic!("Unsupported OS. You must use either Linux, MacOS to build the crate."),
};
let ndk_path = format!("{android_ndk}{lib_dir}");
if std::fs::metadata(&ndk_path).is_err() {
panic!("NDK path does not exist: {ndk_path}");
}
//println!("cargo:warning={target_arch}, {ndk_path}");
println!("cargo:rustc-link-search={ndk_path}");
// The name of the builtins library depends on the target architecture.
match target_arch.as_str() {
"aarch64" => {
println!("cargo:rustc-link-lib=static=clang_rt.builtins-aarch64-android");
}
"arm" => {
println!("cargo:rustc-link-lib=static=clang_rt.builtins-arm-android");
}
"x86_64" => {
println!("cargo:rustc-link-lib=static=clang_rt.builtins-x86_64-android");
}
_ => panic!(
"Unsupported architecture '{target_arch}'. You must use either arm, aarch64 or x86_64 to build the crate."
),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment