cmake 활용하여 c/c++ 함수 사용하기
최근들어 안드로이드 프로젝트에서 c 나 c++ 언어를 사용해야할 일이 생긴다.
이전에는 ndk빌드를 통해서 c 나 c++ 함수를 사용했는데 이번에는 cmake를 사용해보았다.
안드로이드 공식문서에서도 ndk 빌드보다는 cmake 스크립트를 통해 빌드하는 것을 권장하고있다.
Tool - SDK Manager 들어가기
Select Cmake version you want to install
On left Project menu, make foler named by cpp
On cpp folder, we put several files about c++ code
Make CMakeLists.txt in cpp folder
Make cpp file on cpp folder
.cpp file is named "native-lib"
It's okay if you want different file name.
cmake_minimum_required(VERSION 3.4.1)
project("sampleproject")
add_library(
native-lib
SHARED
native-lib.cpp
)
find_library(
native-lib
log
)
target_link_libraries(
native-lib
${logd-lib}
)
Fill the code in CMakeLists.txt like above codes.
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {
arguments += listOf("-DANDROID_STL=c++_shared")
}
}
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
externalNativeBuild {
cmake {
path = File("src/main/cpp/CMakeLists.txt")
version = "3.22.1"
}
}
}
Above code is build.gradle(levle: app)
There is code to build CMakeLists.txt
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_sampleproject_MainActivity_stringFromJni(JNIEnv *env, jobject thiz) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
Define the function we use in MainActivity
class MainActivity : AppCompatActivity() {
val TAG = MainActivity::class.java.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG, "stringFromJni() : ${stringFromJni()}")
}
external fun stringFromJni() : String
}
We can use stringFromJni() function which is defined by c++ code