2

I need to set an environment variable when building an Android app using NDK so that all the CMakeLists.txt files in my NDK project can access that value. Most likely I only need to set that value for this particular app. Any straightforward to do that?

Things I've tried:

I've tried to use a bash script to set the env, and run the script before preBuild during gradle build. I think the script was executed, however, the env var is not set, at least not readable from CMakeLists.txt files. Here's the code in app/build.gradle:

task runBuildScript(type: Exec) {
    commandLine "bash", "-c", './set-env.sh'

}

project.afterEvaluate {
    preBuild.dependsOn(runBuildScript)
}

This is pretty much all the script does:

DIR="${BASH_SOURCE[0]}"
export SDK_BASE=$( cd "$( dirname "$DIR" )/../../" > /dev/null && pwd )

This is how I plan to use that env var in my CMakeLists.txt files:

LIST(APPEND CMAKE_MODULE_PATH "$ENV{SDK_BASE}/build-tools/cmake")
include(sdk_module) # this line will only work if the above command can find the module from the correct location

FYI, I'm using Android Studio on Mac to build this app, if that matters.

odieatla
  • 1,049
  • 3
  • 15
  • 35
  • A shell script (`set-env.sh` in your case) cannot modify environment of the **outer shell**. See e.g. [that question](https://stackoverflow.com/questions/16618071/can-i-export-a-variable-to-the-environment-from-a-bash-script-without-sourcing-i). – Tsyvarev Nov 15 '21 at 16:16

1 Answers1

1

I need to set an environment variable when building an Android app using NDK so that all the CMakeLists.txt files in my NDK project can access that value.

So, you have Gradle invoking CMake?

As described here

If building with Gradle, add arguments to android.defaultConfig.externalNativeBuild.cmake.arguments as described in the ExternalNativeBuild docs. If building from the command line, pass arguments to CMake with -D.

The ExternalNativeBuild docs mention arguments, but there isn't a lot of detail.

Still, you can see examples of externalNativeBuild.cmake.arguments in Gradle in the NDK samples, such as here:

android {
    compileSdkVersion 29
    ndkVersion '22.1.7171670'

    defaultConfig {
        // ...
        externalNativeBuild {
            cmake {
                arguments '-DANDROID_STL=c++_static'
            }
        }
    }
    // ...
    externalNativeBuild {
        cmake {
            version '3.18.1'
            path 'src/main/cpp/CMakeLists.txt'
        }
    }
}
Useless
  • 64,155
  • 6
  • 88
  • 132
  • this works perfectly when passing args directly from gradle to cmake, do you know how to make it work when passing args indirectly as [here](https://stackoverflow.com/q/74247696/9142279)? – HII Oct 29 '22 at 19:18
  • No idea. Literally everything I knew on this subject I learned from the linked documentation and have since forgotten. – Useless Oct 30 '22 at 12:52