Search code examples
androidc++gradleandroid-ndkpreprocessor

How to pass command line arguments from gradlew.bat to Clang on Android/NDK


I'm working with a jenkins script which invokes gradle like so:

./gradlew --info assembleRelease

A lot of our build setup exists within gradle files and this is mostly fine because often we know everything we want to specify for a specific type of build by the Release or Debug nature of it.

We have an exception, however, which is a flag we want to control with a toggle in Jenkins. This flag will turn on or off a C++ macro definition "TEST_MACRO".

Without creating a new build type I was hoping to just pass in a -DTEST_MACRO flag or similar. Can I do that with gradlew?

./gradlew --info assembleRelease -DTEST_MACRO=1

Will that make it to our clang compiler as a globally defined C++ preprocessor definition? Is there a way to do that without needing to construct more variants? (Our actual build system has "googleRelease", "googleDebug", "googleStage", "amazonRelease", "amazonDebug", "amazonStage" for example, and I want to avoid having to have 2x variations of existing configurations just for a single extra cpp define we want to toggle on and off.)


Solution

  • The bounty accepted answer got me most of the way there, but the method of piping gradle -P supplied parameters through was a little different for me. I could not get macros.put to function properly, perhaps I put it in the wrong place.

    The advice I have for anyone who cannot get macros.put to work is to do the following:

    ./gradlew build -PTARGET_SERVER=DEV
    

    Then in your build.gradle file this is an incomplete snippet (requiring your minSdkVersion and all other relevant project setup stuff) of the relevant section which passes cFlags through to the compiled apk:

    apply plugin: 'com.android.application'
    
    android {
        defaultConfig {
            externalNativeBuild.ndkBuild {
                if (project.hasProperty('TARGET_SERVER')) {
                    cFlags += '-DTARGET_SERVER=' + project.TARGET_SERVER
                }
                arguments '-j' + Runtime.runtime.availableProcessors(), 'NDK_TOOLCHAIN_VERSION=clang'
            }
        }
    }