Search code examples
androidgradlebuildandroid-ndk

Pass a variable at build time into externalNativeBuild in Android


Is there a way to pass a constant at compile time into the externalNativeBuild gradle enclosure, and to be able to use it in code?

For example:

externalNativeBuild {
    cmake {
        arguments "-DTEST=" + rootProject.ext.value
    }
}

And the to be able to use it somehow like next:

void foo() {
   int bla = TEST;
   ....
}

Note that the above code is not working, as TEST is not recognized by the c++ compiler, which is what I am trying to solve.


Solution

  • The easiest solution will be to use add_definitions:

    add_definitions(-DTEST=${TEST})
    

    to your CMakeLists.txt file.

    Another one would be to use configuration file

    Basing on Native sample app from Android Studio:

    1. Create file: config.h.in in the same folder as default native-lib.cpp with following contents:

      #ifndef NATIVEAPP1_CONFIG_H_IN
      #define NATIVEAPP1_CONFIG_H_IN
      
      #cmakedefine TEST ${TEST}
      
      #endif //NATIVEAPP1_CONFIG_H_IN
      
    2. In CMakeLists.txt add:

      # This sets cmake variable to the one passed from gradle.
      # This TEST variable is available only in cmake but can be read in
      # config.h.in which is used by cmake to create config.h
      set(TEST ${TEST}) 
      
      configure_file( config.h.in ${CMAKE_BINARY_DIR}/generated/config.h )
      include_directories( ${CMAKE_BINARY_DIR}/generated/ ) 
      

    (add it for example, above add_library call)

    1. Finally, add #include "config.h" in you cod (ex. in native-lib.cpp) to use TEST macro.

    2. Rebuild