Android studio 2.2之後就引入了Cmake 編譯Native code。我們可以通過gradle+cmakelists 配置腳本自動構建native code 生產so庫。
gradle(app/build.gradle)配置:
在
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
......
externalNativeBuild {
cmake {
cppFlags "-frtti -fexceptions"
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
defaultConfig.externalNativeBuild塊是可自定義配置,可以重定義 android.externalNativeBuild塊中內容。詳細
對於這樣一個Android.mk文件
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := TwoDG1
LOCAL_SRC_FILES := Triangle.cpp Square.cpp TwoDG1.cpp
LOCAL_LDLIBS := -lGLESv1_CM -llog
include $(BUILD_SHARED_LIBRARY)
我們改成CMakeLists腳本編譯
add_library( # Sets the name of the library.
TwoDG1
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/native-lib.cpp
src/main/cpp/Triangle.cpp
src/main/cpp/Square.cpp)
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log)
#add lib dependencies
target_link_libraries( # Specifies the target library.
TwoDG1
# Links the target library to the log library
# included in the NDK.
${log-lib}
GLESv1_CM)