Home >Backend Development >C++ >Can I Define LOCAL_SRC_FILES within the ndk {} DSL in Android Gradle?
You may encounter the need to define LOCAL_SRC_FILES within the ndk {} DSL block in your gradle.build file when working with Android Studio projects that include native code. While this is not natively supported by current Gradle plugins, there are several approaches to achieve similar functionality.
In earlier versions of Gradle, you could address this issue by excluding unwanted source files from the build process. However, this approach required disabling the regular NDK build tasks and defining custom ones.
With the introduction of Gradle's experimental plugin (com.android.tools.build:gradle-experimental:0.4.0), you can now exclude files from the NDK build based on patterns. To do so, use the following syntax:
android.sources { main { jni.source { srcDirs = ["~/srcs/jni"] exclude "**/win.cpp" } } }
This allows you to exclude specific files, such as those intended for other platforms (e.g., iOS, WinRT) while targeting Android in your NDK build.
If you require a debuggable setup, a workaround involves building a static library with ndk-build and linking it with the necessary objects to provide the required symbols. This approach requires splitting your native sources into platform-specific and platform-independent files.
In your build.gradle file:
task buildStaticLib(type: Exec, description: 'Compile Static lib via NDK') { commandLine "$ndkBuild", "$staticLibPath", "NDK_PROJECT_PATH=~/srcs", "NDK_OUT=$ndkOut", "APP_ABI=$appAbi", "APP_STL=gnustl_static" } tasks.all { task -> if (task.name.startsWith('link')) { task.dependsOn buildStaticLib } } model { android.ndk { moduleName = "hello-jni" abiFilters += "$appAbi".toString() ldFlags += "$staticLib".toString() ldLibs += "log" cppFlags += "-std=c++11" } android.sources { main.jni.source { srcDirs = ["~/srcs/jni"] } } }
In ~/srcs/Android.mk:
LOCAL_PATH := $(call my-dir)/.. include $(CLEAR_VARS) LOCAL_MODULE := staticLib LOCAL_SRC_FILES := HelloJni.cpp LOCAL_CPPFLAGS += -std=c++11 include $(BUILD_STATIC_LIBRARY)
Alternatively, you can consider using an external tool like CMake or Buck to manage your native code build process and integrate it with Gradle. This approach provides more flexibility and control over the compilation and linking process.
The above is the detailed content of Can I Define LOCAL_SRC_FILES within the ndk {} DSL in Android Gradle?. For more information, please follow other related articles on the PHP Chinese website!