Android studio 使用Cmake完成C/C++ 的使用以及生成so文件
生活随笔
收集整理的這篇文章主要介紹了
Android studio 使用Cmake完成C/C++ 的使用以及生成so文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天,簡單講講android中關于Cmake進行NDK編程的相關知識。
Android studio 2.2版本以后對C/C++的支持可以說很方便了,當然官方推薦使用Cmake完成對C/C++的支持
2.2版本以上的同學新建一個項目就知道了,步驟如下:
File -> New -> New Project,如下圖:
然后勾選Include C++ support,一直next ,最后Finish以后,項目就出現了,和一般的項目略有不同,其實只要多了幾個文件,而已:
1:目錄下多了個CmakeLists.txt文件
2:src目錄下多了一個cpp目錄,里面有個.cpp文件,C++文件都是以.cpp結尾的。
3:就是build.gradle內容中添加了幾行配置
一一解讀一下,先來看看CmakeLists.txt 文件里面的內容是什么:
# 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.add_library( # Sets the name of the library.native-lib# Sets the library as a shared library.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.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 )# 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.native-lib# Links the target library to the log library# included in the NDK.${log-lib} )這里有設置Cmake版本啊,引用的cpp文件的路徑啊等等,如果自己引用的話 其實值需要修改引用的cpp路徑即可,其他的暫時不需要動
看下native_lib.cpp文件內容:
#include <jni.h> #include <string>extern "C" JNIEXPORT jstring JNICALL Java_com_process_main_myapplication_MainActivity_stringFromJNI(JNIEnv* env,jobject /* this */) {std::string hello = "Hello from C++";return env->NewStringUTF(hello.c_str()); }
很簡單 其實就是輸出Hello from C++這段文字:
再看下build.gradle的配置改變:
主要多了兩個地方的改變:
1:defaultConfig中添加:
2:在android{}中添加:
其實也就是引用CmakeLists.txt文件。
現在重點講講CmakeLists.txt里面的代碼的含義。
還有就是要是在add_liberary中添加.cpp文件的話記得路徑,如果你的CMakeLists和你的.cpp在一個問價夾下就不用管路徑。
Android studio 使用Cmake完成C/C++ 的使用以及生成so文件就講完了。
就這么簡單。
總結
以上是生活随笔為你收集整理的Android studio 使用Cmake完成C/C++ 的使用以及生成so文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 获取屏幕的宽高
- 下一篇: android byteBuffer的使