Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android NDK 編譯 Boost 時的 STL 相關錯誤排解

編輯:關於 Android 程式設計

由於 Android 系統並未內建 Boost,而 Boost 大量使用了 STL 與部分 C++ 語言特性,因此在 NDK 下編譯時往往會遇到一連串令人頭痛的典型錯誤。以下把常見問題與解法逐一梳理。

一、異常(Exception)相關錯誤

常見的錯誤訊息如下:

boost/exception/detail/exception_ptr.hpp:382: error: expected ';' before 'catch'
boost/exception/detail/exception_ptr.hpp:387: error: expected primary-expression before 'catch'
boost/throw_exception.hpp:48: error: in passing argument 1 of 'void boost::throw_exception(const std::exception&)'

原因:編譯器預設禁用了 C++ 的異常捕獲機制。
解法:在 Android.mk 中加入 -fexceptions 開啟異常支援即可:

LOCAL_CPPFLAGS += -fexceptions

或者在 Application.mk 中加入 APP_CPPFLAGS += -fexceptions(適用於 Eclipse 環境)。補充一點:只有「異常安全」的程式碼才建議用 -fexceptions 編譯(這其實是編譯 C++ 時的預設選項)。絕大多數 C 程式碼都不是異常安全的,因此當你使用 try{}catch{} 這類關鍵字時,就需要明確加上 -fexceptions。

另外常搭配使用的是 -frtti,它會開啟 RTTI(執行期型別資訊),讓 dynamic_cast、typeid 等特性可用;若想省下空間,也可用 -fno-rtti 關閉。

二、STL 函數找不到、連結失敗

這類錯誤通常長這樣:

error: undefined reference to '__cxa_end_catch'
error: undefined reference to '__cxa_rethrow'
error: undefined reference to '__gxx_personality_v0'
error: undefined reference to 'std::_List_node_base::unhook()'
error: undefined reference to 'std::_List_node_base::hook(std::_List_node_base*)'

其中 __cxa_*、__gxx_personality_v0 這類函數位於 libsupc++.a;而 _List_node_base 相關的則位於 libstdc++.a。把它們正確連結進來即可解決。

在 Android 4.2 系統中,可如此設定:

prebuilt_stdcxx_PATH := prebuilts/ndk/current/sources/cxx-stl/gnu-libstdc++

LOCAL_C_INCLUDES := \
    $(prebuilt_stdcxx_PATH)/include \
    $(prebuilt_stdcxx_PATH)/libs/$(TARGET_CPU_ABI)/include/

LOCAL_CPPFLAGS += -fexceptions -frtti
LOCAL_LDFLAGS += -L$(prebuilt_stdcxx_PATH)/libs/$(TARGET_CPU_ABI) -lgnustl_static -lsupc++

把標頭檔與函式庫都正確引入後,基本上就能解決絕大部分的 STL 連結問題。要特別注意的是:STL 庫要到 Android 4.1 以上版本才完整實作了所有函數。如果你仍遇到某個函數連結失敗,可以下載 Android 4.1/4.2 的原始碼,把 android-4.2_r1/prebuilts/ndk/current/sources 底下的內容打包放進 prebuilt/ndk,再在 Android.mk 中重新定義 prebuilt_stdcxx_PATH 即可。

三、預編譯靜態庫的 MODULE_TAGS 錯誤

編譯預製(prebuilt)靜態庫時,可能會出現以下錯誤:

build/core/base_rules.mk:81: * Each module must use a LOCAL_MODULE_TAGS ...
        * optional, debug, eng, tests, samples

解法是修改 build/core 下的 definitions.mk,在 include-prebuilt 定義中加上 LOCAL_MODULE_TAGS := optional:

define include-prebuilt
    include $$(CLEAR_VARS)
    LOCAL_SRC_FILES := $(1)
    LOCAL_BUILT_MODULE_STEM := $(1)
    LOCAL_MODULE_SUFFIX := $$(suffix $(1))
    LOCAL_MODULE := $$(basename $(1))
    LOCAL_MODULE_CLASS := $(2)
    LOCAL_MODULE_TAGS := optional   // 加上這行即可
    include $$(BUILD_PREBUILT)
endef

之後就能用 add-prebuilt-files 指令輕鬆引入預編譯的靜態庫:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
$(call add-prebuilt-files, STATIC_LIBRARIES, libboost_filesystem.a)
$(call add-prebuilt-files, STATIC_LIBRARIES, libboost_system.a)
$(call add-prebuilt-files, STATIC_LIBRARIES, libboost_thread.a)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved