C++11 on Android
The latest Andoird NDK r8e finally supports some of the most important C++11 library features: thread, mutex, atomic and so on. It is now straightforward to write multi-threaded programs using C++11 on Android, without hacking and jumping through hoops. All you need is downloading NDK r8e.
The most natural way to organize any C/C++ native code for an Android project, is to follow the Google guide: use a jni sub-directory to house Android.mk file (and optionally Application.mk file). The actual source code files, however, could be littered around; just refer them in Android.mk.
To enable C++11 threading, settings in both Application.mk and Android.mk are important. Below is the minimal examples of both files.
# Application.mk
# In NDK r8e, we have to use GCC 4.7 for C++11 features like thread, mutex, etc.
# The default GCC is 4.6, which does NOT define macro _GLIBCXX_HAS_GTHREADS,
# so you’ll get errors like "mutex in namespace std does not name a type" etc.
NDK_TOOLCHAIN_VERSION := 4.7
# GNU STL implements most C++11 features. Use either gnustl_static or gnustl_shared
# Without this your C++ code will not be able to access headers like <thread>, <mutex>
APP_STL := gnustl_static
# Use advanced ARM ABI
APP_ABI := armeabi-v7a
And Android.mk:
# Android.mk
# Regular boilerplate required by NDK
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# C++11 and threading enabling features.
# Otherwise c++11, pthread, rtti and exceptions are not enabled by default
LOCAL_CPPFLAGS := -std=c++11 -pthread -frtti -fexceptions
LOCAL_ARM_MODE := arm
LOCAL_MODULE := foo
LOCAL_SRC_FILES := foo.cpp
include $(BUILD_SHARED_LIBRARY)
Notice the red settings in both files. Now, in foo.cpp, you can include headers like <thread> and <mutex>, and start using std::thread and std::mutex.