はじめに
C/C++のコードをAndroidアプリに埋め込む簡単な方法はNative C++の新規プロジェクトを作成することです。
参考: https://qiita.com/iwatake2222/items/add95edc63d79ca47af9
ここでは個人的な備忘録として、上記手順で作成されるcppフォルダ直下に自動生成されるCMakeファイルの中身をまとめていく。
ファイルの中身
以下のようなフォルダ構成でmainフォルダ直下にcppフォルダが生成される。
フォルダ構成
cpp
├─CMakeLists.txt
└─native-lib.cpp
CMakeファイルの中身
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).
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})
1つずつ詳細を見ていく。
1つ目
cmake_minimum_required(VERSION 3.4.1)
CMakeのバージョンを指定するコマンド。
2つ目
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).
native-lib.cpp)
Java/Kotlinからに取り込むライブラリを指定。
引数はそれぞれ
1. Java/Kotlinから呼び出す際の名前。
2. "SHERED"で固定
3. 取り込むソース。
3つ目
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)
NDK ライブラリを特定して変数にそのパスを保存している。
引数はそれぞれ
1. 検索し特定したNDKライブラリのパスを格納する変数
2. 検索する対象のNDKライブラリ名
4つ目
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の中身も記載しておく。
native-lib.cpp
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_takafumi_bamba_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}