Android Calling C++ in Practice: From Hand-Written JNI to Publishing an AAR

I put together a minimal runnable project, TestNativeCode, and use it as a teaching example. This article follows that project's evolution to unpack the main ways of calling C++ from Android: from the most raw hand-written JNI, to pulling in an external team's source, to working with only a prebuilt .so, using SWIG to auto-generate the glue code, and finally packaging everything into an AAR and publishing it like a normal SDK.
By the end you'll see that the approach you pick really comes down to how you collaborate with the person writing the C++.
The companion code is on GitHub: https://github.com/haydenzhourepo/TestNativeCode. Each section maps to its own commit, so clone it and flip through commits as you read.
Environment Setup
Get the toolchain ready before diving in. The examples below use Windows (where the pitfalls are most numerous); macOS/Linux only differ in paths.
• Android Studio + Android SDK: the baseline, no need to dwell on it.
• NDK: open SDK Manager → SDK Tools, check NDK and CMake to install them. This article uses NDK 28.x and the SDK-bundled CMake 3.22.1.
• CMake and Ninja: what actually does the work in an Android project is the SDK-bundled set (Sdk/cmake/<version>/bin/ contains both cmake and ninja.exe). Later we'll have the script prefer those, to avoid conflicts between a newer system CMake and the NDK toolchain.
• SWIG: used to auto-generate the JNI glue code (only needed from section four). On Windows, winget install swig or scoop install swig is recommended. After installing, confirm swig -version runs — its famous "can't find swig.swg" pitfall gets its own section later.
• Gradle / Android Studio: the build tool; being able to run ./gradlew is enough.
One small reminder: when you run scripts in the terminal, make sure swig, ninja, and cmake are all on PATH. The Gradle inside Android Studio uses its own configured SDK path, which is a different thing from the scripts you run in the terminal — don't mix them up.
Roadmap
We'll go down this path, each step mapping to a real collaboration relationship:
Hand-written JNI
│
▼
Pull in external source (add_subdirectory, compile together)
│
▼
Only a prebuilt .so (standalone cross-compile + import prebuilt lib)
│
▼
Use SWIG to auto-generate the glue code
│
▼
Package into an AAR and publish to local Maven1. The Naive Approach: Hand-Written JNI
Forget the fancy stuff for a moment. We start from a clean Android project (Kotlin + Compose) and aim to have C++ return a string.
Android calls C++ through JNI (Java Native Interface). The mechanism is simple: you declare an external function in Kotlin, implement a function in C++ following a fixed naming rule, and the system wires them together.
C++ side (hayden.cpp):
#include <jni.h>
#include <string>
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_testnativecode_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}Notice that function name
Java_com_example_testnativecode_MainActivity_stringFromJNI it's not arbitrary. The convention is Java_<package>_<class>_<method>, with dots in the package replaced by underscores. Almost everyone trips here on their first try: misspell one letter and you get UnsatisfiedLinkError at runtime.
CMake side (CMakeLists.txt):
cmake_minimum_required(VERSION 3.22.1)
project("testnativecode")
add_library(hayden SHARED hayden.cpp)Kotlin side (MainActivity.kt):
class MainActivity : ComponentActivity() {
companion object {
init {
System.loadLibrary("hayden")
}
}
private external fun stringFromJNI(): String
}System.loadLibrary("hayden") loads libhayden.so; just match the name.
Once this runs, you've got the most fundamental pattern: C++ code + CMake + hand-written JNI bridge + load the library. Simple and direct, but with an obvious downside — you write the bridge functions one by one, and with many functions it drives you up the wall.
2. Scenario One: They Give You Source, You Compile It In
In reality, another team may not hand you just a .so; they may give you the source too and let you compile it. The easiest move then is to pull their code in as a subproject and compile it into your app.
We create an external-lib/ directory at the project root to simulate the "external team's project":
// add.h
int add(int a, int b);
// add.cpp
#include "add.h"
int add(int a, int b) { return a + b; }Then in external-lib/CMakeLists.txt we build it as a static library:
add_library(external-lib STATIC add.cpp)
target_include_directories(external-lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})On the app side, CMake uses add_subdirectory to pull in the external project, then links it:
add_subdirectory(${EXTERNAL_LIB_DIR} ${CMAKE_BINARY_DIR}/external-lib)
target_link_libraries(hayden external-lib ${log-lib})This is the first collaboration mode: copy their source into your project and compile together. The upside is a single .so that's simple to load; the downside is their source enters your repo, which complicates version management.
3. Scenario Two: They Give You Only a Prebuilt .so
The more common case is actually the other one: they don't give you source, only a compiled shared library. Now add_subdirectory is useless — you have no source to compile.
The right move: cross-compile that library standalone, outside the Android project, then copy the resulting .so into the project's jniLibs/ directory. The Android Gradle plugin automatically packs whatever is under jniLibs/ into the APK, with zero extra config.
We wrote a cmake.sh script to do this (illustrative):
cmake -S . -B build/$ABI \
-G Ninja \
-DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
-DANDROID_ABI=$ABI \
-DANDROID_PLATFORM=android-24
cmake --build build/$ABI --target external-lib
cp build/$ABI/libexternal-lib.so ../app/src/main/jniLibs/$ABI/On the app side you can no longer add_subdirectory; instead you treat that prebuilt .so as an imported library (IMPORTED):
add_library(external-lib SHARED IMPORTED)
set_target_properties(external-lib PROPERTIES
IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libexternal-lib.so)
target_link_libraries(hayden external-lib ${log-lib})One easy-to-forget detail: load order. Because hayden depends on external-lib, System.loadLibrary must load the dependency first:
System.loadLibrary("external-lib") // first
System.loadLibrary("hayden") // secondA pitfall here (Windows users take note): running cmake.sh on Windows, CMake defaults to the Visual Studio generator and fails outright, because the Android NDK toolchain only accepts Ninja. So the script must explicitly pass -G Ninja, and ninja must be on PATH (the SDK-bundled CMake package includes ninja.exe).
4. Stop Hand-Writing JNI — Let SWIG Generate It
Those Java_com_example_..._add bridge functions are fundamentally repetitive labor. With dozens or hundreds of functions, hand-writing is madness. This is where SWIG comes in — it reads an interface description file and auto-generates both the JNI C++ glue and the Java proxy classes.
We add an add.i to external-lib:
%module ExternalLib
%{
#include "add.h"
%}
%include "add.h"Then in external-lib/CMakeLists.txt we let CMake invoke SWIG:
add_custom_command(
OUTPUT ${GEN}/native_wrap.cxx ${GEN}/ExternalLib.java ${GEN}/ExternalLibJNI.java
COMMAND ${SWIG_EXECUTABLE} -java -c++ -package com.example.testnativecode.swig
-outdir ${GEN}/java/... -o ${GEN}/native_wrap.cxx add.i
DEPENDS add.i add.h)SWIG does two things:
1.Generates native_wrap.cxx — the JNI bridge functions, compiled directly into libexternal-lib.so;
2.Generates ExternalLib.java / ExternalLibJNI.java — the Java-side proxy classes.
So in Kotlin you no longer declare external fun; you just call it:
import com.example.testnativecode.swig.ExternalLib
// ...
val result = ExternalLib.add(2, 3) // underneath, this is C++'s addThat hand-written addNumbers JNI function can be deleted for good. This is SWIG's value: you only maintain one .i file; when the C++ interface changes, just regenerate.
Another pitfall (still Windows):the SWIG installed via WinGet (the swigwin build) keeps its library files in the Lib/ directory next to swig.exe, but it gets confused by WinGet's symlink and can never find swig.swg. The fix is to resolve SWIG's real path with readlink -f in cmake.sh and point SWIG at that Lib directory via the SWIG_LIB environment variable:
SWIG_REAL="$(readlink -f "$(command -v swig)")"
export SWIG_LIB="$(dirname "$SWIG_REAL")/Lib"5. The Final Step: Package Into an AAR, Use It Like a Normal SDK
Up to here, the functionality is complete. But the project structure is still a bit messy: external-lib's .so and Java proxies are scattered inside the app project.
Real team collaboration should look like this: the person responsible for C++ packages the result into an AAR (Android library) and publishes it; consumers just add one dependency line and never touch native code.
We create a new swiglib library module to hold these things:
1.src/main/jniLibs/x86_64/libexternal-lib.so
2.src/main/java/com/example/testnativecode/swig/ExternalLib*.javaThat is, we change cmake.sh's copy target from the app to this library module.
The whole final structure looks like this:
external-lib/ ← C++ source + SWIG interface add.i
│
│ cmake.sh (NDK cross-compile + swig generates proxies)
▼
libexternal-lib.so + Java proxies (ExternalLib)
│
│ copied into the module's source dir
▼
swiglib/ ← Android library module
│
│ maven-publish → ~/.m2
▼
com.example:swiglib:1.0 (AAR)
│
│ implementation(...) dependency
▼
app/ ← only calls ExternalLib.addThen in this module's build.gradle.kts we publish to local Maven (~/.m2)
afterEvaluate {
publishing {
publications {
create<MavenPublication>("release") {
from(components["release"])
groupId = "com.example"
artifactId = "swiglib"
version = "1.0"
}
}
repositories { mavenLocal() }
}
}The app side becomes squeaky clean — just one dependency line:
implementation("com.example:swiglib:1.0")MainActivity still does ExternalLib.add(2, 3), but now it comes from a proper published artifact, not a pile of loose files in the project.
Note that publishing and consuming must be two separate Gradle invocations. Gradle resolves dependencies during the "configuration phase", while the publish task only runs in the "execution phase". So the correct order is:
./gradlew :swiglib:publishReleasePublicationToMavenLocal
./gradlew :app:assembleDebugPublish to ~/.m2 first, then build the app. Want to publish and build in one line? No — by the second invocation the dependency is already resolved and won't be found. (Alternatively, you could just have the app module depend on the :swiglib module directly; the point here was to demonstrate how to handle it when the two modules live in separate projects.)
Wrapping Up
Looking back, this is actually a clear line of collaboration evolution:
• From hand-written JNI functions, to using add_subdirectory to compile external source in;
• To, when they only give a .so, standalone cross-compile + import the prebuilt library (treat external-lib as an external directory — placing it inside the Android project here is only for demonstration);
• Then using SWIG to automate the most annoying bridge code;
• Finally packaging the whole thing into an AAR published to local Maven (in real work you'd add a remote repo address and publish to the remote on release), so the app consumes it like a normal SDK.
If you're just taking over someone else's C++ code, check which stage you're at — a lot of the time, what stalls you isn't that JNI is hard, but that you haven't thought through which way to bring it in.
One last note: the code for this tutorial is on GitHub: https://github.com/haydenzhourepo/TestNativeCode
