Android studio 使用Cmake完成C/C++ 的使用以及生成so文件

Android studio 2.2版本以后对C/C++的支持可以说很方便了,当然官方推荐使用Cmake完成对C/C++的支持

2.2版本以上的同学新建一个项目就知道了,步骤如下:

File -> New -> New Project,如下图:

Android studio 使用Cmake完成C/C++ 的使用以及生成so文件

然后勾选Include C++ support,一直next ,最后Finish以后,项目就出现了,和一般的项目略有不同,其实只要多了几个文件,而已:

Android studio 使用Cmake完成C/C++ 的使用以及生成so文件


1:目录下多了个CmakeLists.txt文件

2:src目录下多了一个cpp目录,里面有个.cpp文件,C++文件都是以.cpp结尾的。

3:就是build.gradle内容中添加了几行配置

一一解读一下,先来看看CmakeLists.txt 文件里面的内容是什么:

[java] view plain copy
  1. # For more information about using CMake with Android Studio, read the  
  2. # documentation: https://d.android.com/studio/projects/add-native-code.html  
  3.   
  4. # Sets the minimum version of CMake required to build the native library.  
  5.   
  6. cmake_minimum_required(VERSION 3.4.1)  
  7.   
  8. # Creates and names a library, sets it as either STATIC  
  9. # or SHARED, and provides the relative paths to its source code.  
  10. # You can define multiple libraries, and CMake builds them for you.  
  11. # Gradle automatically packages shared libraries with your APK.  
  12.   
  13. add_library( # Sets the name of the library.  
  14.              native-lib  
  15.   
  16.              # Sets the library as a shared library.  
  17.              SHARED  
  18.   
  19.              # Provides a relative path to your source file(s).  
  20.              src/main/cpp/native-lib.cpp )  
  21.   
  22. # Searches for a specified prebuilt library and stores the path as a  
  23. # variable. Because CMake includes system libraries in the search path by  
  24. default, you only need to specify the name of the public NDK library  
  25. # you want to add. CMake verifies that the library exists before  
  26. # completing its build.  
  27.   
  28. find_library( # Sets the name of the path variable.  
  29.               log-lib  
  30.   
  31.               # Specifies the name of the NDK library that  
  32.               # you want CMake to locate.  
  33.               log )  
  34.   
  35. # Specifies libraries CMake should link to your target library. You  
  36. # can link multiple libraries, such as libraries you define in this  
  37. # build script, prebuilt third-party libraries, or system libraries.  
  38.   
  39. target_link_libraries( # Specifies the target library.  
  40.                        native-lib  
  41.   
  42.                        # Links the target library to the log library  
  43.                        # included in the NDK.  
  44.                        ${log-lib} )  
这里有设置Cmake版本啊,引用的cpp文件的路径啊等等,如果自己引用的话 其实值需要修改引用的cpp路径即可,

其他的暂时不需要动

看下native_lib.cpp文件内容:

[java] view plain copy
  1. #include <jni.h>  
  2. #include <string>  
  3.   
  4. extern "C"  
  5. JNIEXPORT jstring JNICALL  
  6. Java_com_process_main_myapplication_MainActivity_stringFromJNI(  
  7.         JNIEnv* env,  
  8.         jobject /* this */) {  
  9.     std::string hello = "Hello from C++";  
  10.     return env->NewStringUTF(hello.c_str());  
  11. }  
很简单 其实就是输出Hello from C++这段文字:

再看下build.gradle的配置改变:

[java] view plain copy
  1. apply plugin: 'com.android.application'  
  2.   
  3. android {  
  4.     compileSdkVersion 25  
  5.     buildToolsVersion "25.0.2"  
  6.     defaultConfig {  
  7.         applicationId "com.process.main.myapplication"  
  8.         minSdkVersion 22  
  9.         targetSdkVersion 25  
  10.         versionCode 1  
  11.         versionName "1.0"  
  12.         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"  
  13.         externalNativeBuild {  
  14.             cmake {  
  15.                 cppFlags ""  
  16.             }  
  17.         }  
  18.     }  
  19.     buildTypes {  
  20.         release {  
  21.             minifyEnabled false  
  22.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'  
  23.         }  
  24.     }  
  25.     externalNativeBuild {  
  26.         cmake {  
  27.             path "CMakeLists.txt"  
  28.         }  
  29.     }  
  30. }  
  31.   
  32. dependencies {  
  33.     compile fileTree(dir: 'libs', include: ['*.jar'])  
  34.     androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {  
  35.         exclude group: 'com.android.support', module: 'support-annotations'  
  36.     })  
  37.     compile 'com.android.support:appcompat-v7:25.1.1'  
  38.     compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'  
  39.     testCompile 'junit:junit:4.12'  
  40. }  
主要多了两个地方的改变:

1:defaultConfig中添加:

[java] view plain copy
  1. externalNativeBuild {  
  2.             cmake {  
  3.                 cppFlags ""  
  4.             }  
  5.         }  
2:在android{}中添加:

externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}
其实也就是引用CmakeLists.txt文件。


说到这里,大致知道C++项目的大致结构了。那么原始项目怎么添加C++呢,步骤如下:

1,现在src/main目录下新建cpp目录和java目录同级,然后在cpp目录中新建一个.cpp文件,这里以native-lib.cpp为例子直接copy进去

2,右键项目(选中项目,然后右键)如下:

Android studio 使用Cmake完成C/C++ 的使用以及生成so文件

选择第二个Link C++  Project  with Gradle,出现以下界面:

Android studio 使用Cmake完成C/C++ 的使用以及生成so文件

关于Project Path是选择CmakeLists.txt文件的路径,这里先把之前的CmakeLists.txt文件直接copy过来,然后相应的修改即可:

Android studio 使用Cmake完成C/C++ 的使用以及生成so文件

选择CmakeLists文件然后点击OK按钮。修改CmakeLists.txt文件中的cpp文件引用目录即可(add_library {第三行})。

接下来,在java代码中调用C++代码啦,看下MainActivity中的代码:

[java] view plain copy
  1. public class MainActivity extends AppCompatActivity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.   
  8.     // Example of a call to a native method  
  9.     TextView tv = (TextView) findViewById(R.id.sample_text);  
  10.     tv.setText(stringFromJNI());  
  11.     }  
  12.   
  13.     /** 
  14.      * A native method that is implemented by the 'native-lib' native library, 
  15.      * which is packaged with this application. 
  16.      */  
  17.     public native String stringFromJNI();  
  18.   
  19.     // Used to load the 'native-lib' library on application startup.  
  20.     static {  
  21.         System.loadLibrary("native-lib");  
  22.     }  
  23. }  
这里注意System.loadLibrary("native-lib"),加载(native-lib)Library,这里是CmakeLists文件中配置好的Library名字要对应。

然后就是native调用stringFromJNI ()方法啦》

最后编译一下app,Make Project  build一下,然后run到手机上就可以运行了。

这里有同学想问那.so文件在哪里找啊 ,如下图:

Android studio 使用Cmake完成C/C++ 的使用以及生成so文件

这里的so文件就可以用到其他项目中啦;

至此一个简单的使用C++项目就完成啦