Getting started
Project structure
A typical CMake-based NDK project:By convention, CMake files are placed in a
cpp/ directory, but you can use any name.Basic setup
1
Create the cpp directory
Create a directory for your native code:
2
Create CMakeLists.txt
Define your build configuration:
CMakeLists.txt
3
Configure Gradle
Link CMake in your
build.gradle:build.gradle
4
Build your project
Run your Gradle build. The Android Gradle Plugin will invoke CMake automatically:
CMakeLists.txt basics
Minimum configuration
Every CMakeLists.txt needs these elements:CMakeLists.txt
Library types
- Static library
- Imported library
Adding source files
CMakeLists.txt
Configuring the build
Include directories
CMakeLists.txt
Compiler flags
- Target-specific
- Global
Prefer target-specific settings with
target_* commands. Global settings can affect third-party dependencies unexpectedly.Linking libraries
CMakeLists.txt
Android-specific CMake
Android variables
The NDK toolchain provides these variables:Platform-specific code
CMakeLists.txt
Build type configuration
CMakeLists.txt
Working with third-party libraries
Adding subdirectories
CMakeLists.txt
Using find_package
CMakeLists.txt
Prebuilt libraries
CMakeLists.txt
Multiple modules
Organize complex projects with multiple libraries:CMakeLists.txt
Advanced features
Custom commands
CMakeLists.txt
Option flags
CMakeLists.txt
Installation rules
CMakeLists.txt
Building from command line
Build with CMake directly (without Gradle):When using Gradle integration, you typically don’t need to invoke CMake directly. Gradle handles the toolchain configuration automatically.
Common issues
CMake version mismatch
version in your build.gradle externalNativeBuild.cmake block:
Undefined references
- Ensure all source files are added to
add_library() - Link required libraries with
target_link_libraries() - Check library order (dependencies should come after libraries that use them)
Include path issues
target_include_directories():
ABI-specific libraries not found
${ANDROID_ABI} to reference the correct ABI directory:
Next steps
Gradle integration
Configure CMake in your Gradle build
Build overview
Compare CMake with ndk-build
ABIs
Learn about Android binary interfaces
Debugging
Debug your CMake-built native code