Easy-Peasy Implement a C++ Library in Your Project via Android NDK CMake 🥴[PRACTICAL]

Shubham Kumar Gupta
Stackademic
Published in
5 min readJun 3, 2023

--

Will try to deliver this as a context between two “close” friends Sheila and Mohan!

Mohan: Mutual Funds: म्यूचुअल फंड निवेश बाजार जोखिम के अधीन है, लेकिन अगर कोई निवेशक लंबी अवधि के लिए निवेश करता है तो जोखिम कारक कम हो जाता है जबकि म्यूचुअल फंड रिटर्न अधिकतम हो जाता है …. while reading the newspaper. Oh! Hey Sheila have read that we should be aware of investments! 📰 👓

Sheila: Yeah! but I’m stuck with something WTL. 🥴 😾
Mohan: Ok, btw what’s the issue, or where are you stuck?

Sheila: I just heard about in Android we can run C++ functions too, but I’m trying, and hell lots of errors are coming in and i don’t to fix them.

Mohan: Let me wear my specs 🥸 hmm, lets start now, just to avoid any misconceptions, let's start from the beginning.. ok?

Sheila: Yeah!

Mohan: So, Android NDK or the Native Development Kit is a set of tools that allows one to use C/C++ code with Android as part of their code, and provides platform libraries one can use to manage native activities and access physical devices such as sensors. And it’s provided by Google!. These are some advantages of using it:-

  • Performance Optimization: Computationally intensive tasks, such as graphics rendering or audio processing, can be more efficiently implemented using native code, thus improving performance.
  • Porting Existing Code: It allows one to reuse already C/C++ written code to integrate!
  • Accessing Native APIs: It provides bindings to various native APIs that are not available in the Java or Kotlin frameworks, allowing one to access low-level system functionality.

Sheila:

Sheila: So, what’s inside this set of tools?

Mohan: These contain native compilers, debuggers, build systems, etc.

Mohan: Let’s create an Android project by opening Android Studio. You can choose native if you start from scratch or choose Empty Views Acitivity.

Mohan: Now lets hover for to SDK Tools section to install NDK

Sheila: Wait let me complete it till here!
Mohan: ok!

Mohan: Now let’s head on to this file “local.properites” and add this line

## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
# sdk.dir = [YOUR FOLDER PATH WHERE IT'S INSTALLED]
# ndk.dir = [YOUR FOLDER PATH WHERE IT'S INSTALLED WITH VERSION]

sdk.dir=/Users/MohanCloseFriend/Library/Android/sdk
ndk.dir=/Users/MohanCloseFriend/Library/Android/sdk/ndk/25.2.9519653

Now create a folder named “cpp” inside My Application “src/main/cpp” and create a file named “cpp_code.cpp” and “CMakeLists.txt”, Now this cpp_code you want to act as link between your project and C++.

CMake is a cross-platform build system that allows developers to write build scripts that can be used on different operating systems and platforms, including Android. By using CMake, you can write build configurations that work consistently across different development environments.

Now, Lets’ create a “CMakeLists.txt”

cmake_minimum_required(VERSION 3.22.1)

project(cpp_code)

set(PROJECT_NAME cpp_code)

aux_source_directory(src/main/cpp/ FILE_CPP)
aux_source_directory(src/main/cpp/folder2 FILE_CPP2)
# in case you want to add multiple directories
SET(ALL_FILE ${FILE_CPP} {FILE_CPP2})


add_library( # Sets the name of the library.
cpp_code

# Sets the library as a shared library.
SHARED

# Provides a relative path to your source file(s).
${ALL_FILE})

find_library( # Sets the name of the path variable.
cpp_code

# 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.
cpp_code
android
log
# Links the target library to the log library
# included in the NDK.
${log-lib})

target_sources(
cpp_code

PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/MySecretFileToBeIncluded.h

PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/cpp_code.cpp
)

Now open “app> build.gradle” and add these

android {
...

defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags '-std=c++17'
}
}
ndk {
abiFilters 'armeabi-v7a','arm64-v8a','x86','x86_64'
}
}
...
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
version '3.22.1' //Check version of CMake you install
}
}

Sheila: Wait. I’m done! Will this ever finish?

Mohan: Just hold for 2 more minutes! 😉 can you bare it?

Sheila: Ok, last 2 mins!

Mohan: Open your MainActivity.kt file and add these

//at the end
companion object
{
// Used to load the 'native-lib' library on application startup.
init
{
System.loadLibrary("cpp_code")
}
}

Now create a function inside this MainActivity.kt from where you wanna call the cpp function

external fun helloWorld(
count: Int
): String

/*
* @Lets' invoke the function somwehere
*/

...

Log.d("NDK","Hey! Shiela, ${helloWorld(2)}")

Now we need a function “helloWorld()” inside our “cpp_code.cpp”

Now tap Create JNI function and create a function! This will create a function inside “cpp_code.cpp

extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_application_MainActivityKt_helloWorld(
JNIEnv *env,
jclass clazz,
jint count) {

string hello = "Hello from C++ " + to_string(count) ;
return env->NewStringUTF(hello.c_str());
}

Sheila: Is it done?

Mohan: Yes!! 🥴

You will get the log print!

Sheila: Thanks for mentioning everything that I needed. 😀

Mohan: Bas??! ok will learn audio processing next :> Can we?

Sheila: Sure! Bye!

Me: Thank you everyone for reading this article! Do like if you like this! 😏

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X), LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.

--

--