有個 Android 專案需要使用 boost 標準 C++ 庫。Boost 是可移植、提供源碼的 C++ 庫,作為標準庫的後備,也是 C++ 標準化進程的發動機之一,因此想把它移植到 Android 上編譯。
我先是直接從網路下載 boost 1.52 版並自行寫 makefile 編譯,結果碰到無數錯誤。求助 Google 後,發現一個好用的專案——一個透過 NDK 編譯 boost 的 git 專案:https://github.com/MysticTreeGames/Boost-for-Android。折騰一番後終於編譯成功。以下記錄主要過程:
該專案說明目前支援的 boost 版本為 1.45.0、1.48.0 與 1.49.0,因此下載最新的 1.49 版,完成後準備打補丁。
https://github.com/MysticTreeGames/Boost-for-Android/tree/master/patches/boost-1_49_0
將 boost_1_49_0.tar.bz2 放在 android 的 external 下解壓:
tar -xjvf external/boost_1_49_0.tar.bz2
將 boost-1_49_0.patch 放在 external\boost_1_49_0 根目錄執行:
patch -Np1 -d external/boost_1_49_0 < external/boost_1_49_0/boost-1_49_0.patch
LOCAL_PATH:= $(call my-dir)
common_SRC_FILES := \
libs/thread/src/pthread/thread.cpp \
libs/thread/src/pthread/once.cpp \
common_SRC_FILES += \
libs/filesystem/v3/src/codecvt_error_category.cpp \
libs/filesystem/v3/src/operations.cpp \
libs/filesystem/v3/src/path.cpp \
libs/filesystem/v3/src/path_traits.cpp \
libs/filesystem/v3/src/portability.cpp \
libs/filesystem/v3/src/utf8_codecvt_facet.cpp \
libs/system/src/error_code.cpp \
libs/system/src/local_free_on_destruction \
include $(CLEAR_VARS)
LOCAL_MODULE:= libboost
LOCAL_SRC_FILES := $(common_SRC_FILES)
prebuilt_stdcxx_PATH := prebuilts/ndk/current/sources/cxx-stl/gnu-libstdc++
LOCAL_C_INCLUDES := \
$(LOCAL_PATH)/boost \
$(prebuilt_stdcxx_PATH)/include \
$(prebuilt_stdcxx_PATH)/libs/$(TARGET_CPU_ABI)/include/ \
LOCAL_CFLAGS += -fvisibility=hidden -lpthread
LOCAL_CPPFLAGS += -fexceptions -frtti
LOCAL_SHARED_LIBRARIES := libc libstdc++ libstlport
LOCAL_LDFLAGS += -L$(prebuilt_stdcxx_PATH)/libs/$(TARGET_CPU_ABI) -lgnustl_static -lsupc++
LOCAL_MODULE_TAGS := optional
include $(BUILD_SHARED_LIBRARY)
其中最重要的是上述 -fexceptions -frtti 等設定。最後編譯過程會逐一列出各原始檔的編譯訊息,最終成功生成 libboost.so 庫。
更多Android相關信息見Android 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=11