Android-NDK學習記錄1-環境配置
阿新 • • 發佈:2018-11-25
一. Android Studio配置
(一) 元件下載
- 要使用和除錯,先下載NDK元件:
- NDK包:這套工具集允許您為 Android 使用 C 和 C++ 程式碼,並提供眾多平臺庫,讓您可以管理原生 Activity 和訪問物理裝置元件,例如感測器和觸控輸入。
- cmake:一款外部構建工具,可與 Gradle 搭配使用來構建原生庫。如果您只計劃使用 ndk-build,則不需要此元件。
- LLDB:一種除錯程式,Android Studio 使用它來除錯原生程式碼。
勾選如上圖所示三項即可。這個不用經常更新,特別是NDK,一般有新版本出來了會提示你,但是不用隨意更新,因為有可能更新到比較新的版本,你之前的版本編譯就不行了哦,改起來還挺麻煩的,嘿嘿,特別是針對含有第三方庫編譯的情況。
(二) 配置
Android新版本推薦使用CMake,這裡講的都是CMake,使用的指令碼為CMakeLists.txt
-
如果是新建專案,則勾選C++支援即可完成建立
-
如果是老專案:
- 在main目錄下新建cpp的原生程式碼目錄,然後再建立一個native-lib.cpp的c++檔案
- 在module下新建檔案:CMakeLists.txt
- 連結到gradle中,目的通過gradle來識別編譯指令碼,在執行的時候以依賴的方式來執行CMake
- gradle配置
android { defaultConfig { externalNativeBuild { cmake { //這裡是打包x86的so,可以改為armabi-v7a等 arguments "-DANDROID_ABI=x86" cppFlags "" } } } externalNativeBuild { cmake { path "CMakeLists.txt" } } }
- CMakeLists.txt基本內容如下:
- add_library:配置我們庫的名稱、型別、和編譯檔案
- find_library:找尋ndk中的提供的原生庫
- target_link_libraries:連結指定的庫到我們庫中
# For more information about using CMake with Android Studio, read the # documentation: https://d.android.com/studio/projects/add-native-code.html # Sets the minimum version of CMake required to build the native library. cmake_minimum_required(VERSION 3.4.1) # Creates and names a library, sets it as either STATIC # or SHARED, and provides the relative paths to its source code. # You can define multiple libraries, and CMake builds them for you. # Gradle automatically packages shared libraries with your APK. #指定需傳入三個引數(準備打包生成so函式庫名稱,庫型別,依賴原始檔相對路徑即程式碼路徑) add_library( # Sets the name of the library. my_native_lib # SHARED 動態連結庫 STATIC 靜態連結庫 SHARED # Provides a relative path to your source file(s). src/main/cpp/native-lib.cpp ) # Searches for a specified prebuilt library and stores the path as a # variable. Because CMake includes system libraries in the search path by # default, you only need to specify the name of the public NDK library # you want to add. CMake verifies that the library exists before # completing its build. # 用於定位NDK中的庫,通過find來找到,並取個path變數 # 需要傳入兩個引數(path變數、ndk庫名稱) find_library( # Sets the name of the path variable. #變數名取為log-lib log-lib # Specifies the name of the NDK library that # you want CMake to locate. #找ndk中的log庫,即找ndk中的包為liblog.so log ) # Specifies libraries CMake should link to your target library. You # can link multiple libraries, such as libraries you define in this # build script, prebuilt third-party libraries, or system libraries. # 指定關聯到原生庫的庫 target_link_libraries( # Specifies the target library. #我們的庫,與前面的name保持一致 my_native_lib # Links the target library to the log library # included in the NDK. #要連結進來的庫,如上面指定的path ${log-lib} )
- 最後的專案結構如下:
到此,基礎配置完成。下一篇開始學習下使用