Search code examples
androidc++cmakejava-native-interface

Cpp flags in Android JNI - change variable based on flag


I would like to pass variable to cpp library in android module in order to achieve something like that:

//imports..
using namespace std;

extern "C" {

bool logsEnabled = false;

#ifdef LOGS
logsEnabled = true;
#endif

void android_log(const char *text) {
    if (logsEnabled) {
        __android_log_print(ANDROID_LOG_DEBUG, "TAG", "%s", text);
    }
} ;

//other methods declaration

CppFlags are passed in gradle:

android{
 defaultConfig{
    externalNativeBuild{
      cmake{
           cppFlags '-DLOGS'

Unfortunelly the compiler doesn't see daclaration for logsEnabled in block #ifdef - #endif:

Error:(27, 1) error: C++ requires a type specifier for all declarations

Solution

  • You are probably looking for something like:

    #ifdef LOGS
    bool logsEnabled = true;
    #else
    bool logsEnabled = false;
    #endif
    

    Or perhaps just simpler:

    void android_log(const char *text) {
    #ifdef LOGS
        __android_log_print(ANDROID_LOG_DEBUG, "TAG", "%s", text);
    #endif
    }