Cross-Compiling C/C++ Native External Libraries for Android
In this post, I assume that you are an Android developer who wants to code some parts of an application using C/C++ and the Android NDK. You will find all the needed information about compiling, linking your C/C++ code or pre-built library to your application in the official documentation. Here, I’m going to explain the process of building an external native library using the Android NDK Toolchain to be able to use it in your application.
I also suppose that you know your way around the bash or any UNIX like command-line interpreter. These instructions were tested on a Mac.
Instructions
- Grab the Android NDK and set an environmental variable to its location. Consider to add the environmental variables to your ~/.bash_profile or ~/.bashrc to be always available in your terminal.
export ANDROID_NDK_HOME="$NDK_LOCATION/ndk-bundle"
- Install the toolchain.
${ANDROID_NDK_HOME}/build/tools/make-standalone-toolchain.sh --platform=android-16 --install-dir=${ANDROID_NDK_HOME}/android-toolchain
- Add the toolchain to the PATH environmental variable as well as the following environmental variables.
export PATH="$PATH:$ANDROID_NDK_HOME/android-toolchain/bin"
export CC="arm-linux-androideabi-gcc"
export CXX="arm-linux-androideabi-g++"
export RANLIB="arm-linux-androideabi-ranlib"
export LD="arm-linux-androideabi-ld"
export AR="arm-linux-androideabi-ar"
export CROSS_COMPILE="arm-linux-androideabi"
#Define the Android API level
export ANDROID_API=16
export CFLAGS="-D__ANDROID_API__=$ANDROID_API"
- Configure and make your library.
Please note that the arguments are library specific. However, in general you will need to specify the host, the prefix (The installation directory upon make install) etc…
$./configure android --host=${CROSS_COMPILE} --disable-shared --prefix="${ANDROID_NDK_HOME}/Pre-built/libName"$make$make install
- Add the static library to Android Studio according to this guide.
My pre-built libraries
I’ve setup a Git repository in which you will find the above instructions and my pre-built libraries. I will be updating this repo from time to time. Feel free to send me a pull request to add additional libraries.
Note
If you encountered “Invalid configuration `arm-linux-androideabi`” while configuring your library. You will need to update the autotools autoconf’s ‘config.guess’ and ‘config.sub’. You will find them in the ‘updated_config’ directory of the repository or you may download the latest ones from this repository.
These are the instructions to compile a C/C++ native libraries for the arm architecture only. Compiling to other architectures [aarch64-linux-android, mips64el-linux-android, mipsel-linux-android, x86, x86_64] should be straightforward.
If you are familiar with ndk-build, you may use it also to compile a C/C++ native libraries to multiple-architectures.
Conclusion
I hope that the instructions were clear. I’ll be happy to clarify anything if you have any questions.