由於 Android 系統目前並未將 boost 納入,而其中大量使用了 STL 及部分 C++ 語言特性,導致編譯時出現令人頭痛的問題。
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/date_time/constrained_value.hpp:110: error: invalid initialization of reference of type 'const std::exception&' from expression of type 'boost::CV::simple_exception_policy<short unsigned int, 1u, 366u, boost::gregorian::bad_day_of_year>::exception_wrapper'
boost/throw_exception.hpp:48: error: in passing argument 1 of 'void boost::throw_exception(const std::exception&)'
此問題源於編譯器的異常捕獲被禁用,需在 Android.mk 中開啟。加入以下設定即可:
LOCAL_CPPFLAGS += -fexceptions
或在 Application.mk 中加入 APP_CPPFLAGS += -fexceptions(Eclipse 下編譯)。此外,Android 平台提供了最小化的 C++ 運行庫(/system/lib/libstdc++)及對應頭檔。
只有異常安全的程式碼才適合用 -fexceptions 編譯(編譯 C++ 時這是預設選項)。絕大多數 C 程式碼都不是異常安全的:若未加 -fexceptions,異常經過時程式會直接退出;加了之後,萬一它調用的某函數拋出異常,也會直接經過這段程式碼,處理不好可能出現記憶體洩漏等問題而不報錯。因此使用 try{}catch{} 關鍵字時需加上 -fexceptions。
-frtti:打開 rtti(runtime type identification),編譯器會為每個有虛函數的類添加資訊以支援 dynamic_cast、typeid 等特性;可用 -fno-rtti 關閉以節約空間。