1. 程式人生 > >Android studio 使用Cmake完成C/C++ 的使用以及生成so檔案

Android studio 使用Cmake完成C/C++ 的使用以及生成so檔案

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的配置改變:

apply plugin: 'com.android.application'
 
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.process.main.myapplication"
        minSdkVersion 22
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}
 
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    testCompile 'junit:junit:4.12'
}

主要多了兩個地方的改變:

1:defaultConfig中新增:

externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }

2:在android{}中新增:

externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}

其實也就是引用CmakeLists.txt檔案。

說到這裡,大致知道C++專案的大致結構了。那麼原始專案怎麼新增C++呢,步驟如下:

1,現在src/main目錄下新建cpp目錄和java目錄同級,然後在cpp目錄中新建一個.cpp檔案,這裡以native-lib.cpp為例子直接copy進去

2,右鍵專案(選中專案,然後右鍵)如下:

選擇第二個Link C++  Project  with Gradle,出現以下介面:

關於Project Path是選擇CmakeLists.txt檔案的路徑,這裡先把之前的CmakeLists.txt檔案直接copy過來,然後相應的修改即可:

選擇CmakeLists檔案然後點選OK按鈕。修改CmakeLists.txt檔案中的cpp檔案引用目錄即可(add_library {第三行})。

接下來,在java程式碼中呼叫C++程式碼啦,看下MainActivity中的程式碼:

public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
    // Example of a call to a native method
    TextView tv = (TextView) findViewById(R.id.sample_text);
    tv.setText(stringFromJNI());
    }
 
    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
 
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }
}

這裡注意System.loadLibrary("native-lib"),載入(native-lib)Library,這裡是CmakeLists檔案中配置好的Library名字要對應。

然後就是native呼叫stringFromJNI ()方法啦》

最後編譯一下app,Make Project  build一下,然後run到手機上就可以運行了。

這裡有同學想問那.so檔案在哪裡找啊 ,如下圖:

這裡的so檔案就可以用到其他專案中啦;

至此一個簡單的使用C++專案就完成啦