Friday, October 27, 2017

Build OpenCV for Android with LLVM C++ Runtime

According to the Android NDK C++ Library Support, LLVM's libc++ will be the only STL:
LLVM's libc++ is the C++ standard library that has been used by the Android OS since Lollipop, and in the future will be the only STL available in the NDK.Until NDK r16, the NDK's libc++ is only of beta quality. Beginning with NDK r16, libc++ will be the preferred STL. A future NDK release will remove the other options.
If you are working with libraries linked with gnustl, you may have big problems.
In this post, I introduce how I compile the OpenCV for Android with LLVM libc++ runtime.

Install the cmake and cmake-gui

1. Dont install by sudo apt-get install (or update) cmake. Depends on the different Ubuntu version, you may not get the latest cmake installed.
2. Uninstall the existing cmake: sudo apt-get purge cmake
3. Download pre-compiled cmake package: Latest Release (3.9.4)
4. Install the cmake (cmake-gui is also included)

Download the OpenCV source

OpenCV is available from github.
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git (Optional)

Cmake configuration

1. Start cmake-gui
2. Click the "Browse Source" button and give the OpenCV source folder
3. Click the "Browse Build" button and give the build folder (e.g. create a folder: opencv_android_build)
4. Click "Configure" button, select "Specify toolchain file for cross-compiling", in the next prompt window, make sure to select the "android.toolchain.cmake" under HOME_NDK/build/cmake/. Make sure not to use the file under opencv folder!!!
5. Click "Add Entry" button, add ANDROID_PLATFORM as String with value android-21
6. Click "Add Entry" button, add ANDROID_STL as String with value c++_static
7. Change the existing item CMAKE_BUILD_TYPE to Release
8. Change the existing item CMAKE_CXX_STANDARD_LIBRARIES to libc++_static.a from  libgnustl_static.a (under HOME_NDK/sources/cxx-stl/llvm-libc++/libs/armeabi-v7a/)
9. Click "Configure" button to configure again
10. Click "Generate" button to generate configuration
11. Go to the build folder (e.g. opencv_android_build), run make -j to make the targets
12. Run make install, the final files will be found under install folder.

Good luck!