Build native code with CMake and the Android NDK toolchain
CMake is a cross-platform build system that works seamlessly with the Android NDK. It provides a modern, declarative syntax for building native libraries and is the recommended build system for new NDK projects.
# List files explicitly (recommended)add_library(mylib SHARED file1.cpp file2.cpp subdir/file3.cpp)# Use variables for organizationset(SOURCES file1.cpp file2.cpp subdir/file3.cpp)add_library(mylib SHARED ${SOURCES})# Use GLOB for simple projects (not recommended for large projects)file(GLOB SOURCES "src/*.cpp")add_library(mylib SHARED ${SOURCES})
Using file(GLOB) can cause CMake to miss file changes. For production projects, list source files explicitly.
# Add include paths to a targettarget_include_directories(mylib PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/../external/headers)# Export includes to dependent targetstarget_include_directories(mylib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
# Set C++ standard (recommended)set_target_properties(mylib PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON)# Add compile optionstarget_compile_options(mylib PRIVATE -Wall -Wextra -Werror)# Add definitionstarget_compile_definitions(mylib PRIVATE MY_DEFINE=1 DEBUG_MODE)
# Set global C++ standardset(CMAKE_CXX_STANDARD 17)set(CMAKE_CXX_STANDARD_REQUIRED ON)# Global compile optionsadd_compile_options(-Wall -Wextra)# Global definitionsadd_definitions(-DMY_GLOBAL_DEFINE)
Prefer target-specific settings with target_* commands. Global settings can affect third-party dependencies unexpectedly.
# Find Android system librariesfind_library(log-lib log)find_library(android-lib android)# Link libraries to your targettarget_link_libraries(mylib ${log-lib} ${android-lib})# Link with other CMake targetsadd_library(utils STATIC utils.cpp)target_link_libraries(mylib utils)# Link with imported librariesadd_library(prebuilt SHARED IMPORTED)set_target_properties(prebuilt PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${ANDROID_ABI}/libprebuilt.so)target_link_libraries(mylib prebuilt)
# Single prebuilt libraryadd_library(ssl SHARED IMPORTED)set_target_properties(ssl PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/${ANDROID_ABI}/libssl.so)# Link with your targettarget_link_libraries(mylib ssl)