How to cross compile 4 Android
In order to cross-compile a C++ library for Android, we have to prepare a custom toolchain. We exercise this with the OSCPACK library by creating a CMake build file that uses the custom toolchain.
So first we download the OSCPACK sources:
git clone https://github.com/MariadeAnton/oscpack.git
Then we assume that we have downloaded and unpacked the Android NDK. I am using android-ndk-r12b in this example.
Then the build/tools directory of the NDK contains a Python script, which will create an archive with a stand-alone toolchain. This toolchain archive contains all necessary cross-compilers and related tools to compile for Android. So let’s create a toolchain with the script:
cd build/tools ./make_standalone_toolchain.py —arch arm —api 16
Then we extract the resulting tar archive into /opt.
Now we have a C cross compiler in
/opt/arm-linux-androideabi/bin/arm-linux-androideabi-gcc
And we have a C++ cross compiler in
/opt/arm-linux-androideabi/bin/arm-linux-androideabi-g++
Next step is to tell the CMake build file of OSCPACK to use those compilers instead of the default ones. We do so by prepending the following to the CMakeLists.txt build file:
set(CMAKE_SYSTEM_NAME Android) set(CMAKE_C_COMPILER /opt/arm-linux-androideabi/bin/arm-linux-androideabi-gcc) set(CMAKE_CXX_COMPILER /opt/arm-linux-androideabi/bin/arm-linux-androideabi-g++)
And finally we cross-compile the OSCPACK library for Android:
cmake . && make
This produces a liboscpack.a library archive that can be added as extra file to link with in your Android project.