Search code examples
androidandroid-studioandroid-ndkandroid-productflavors

Splitting c++ files between multiple product flavours


My Android Studio module has two product flavours:

flavour1 uses NDK and incudes cpp files, whereas flavour2 doesn't use NDK and should not include cpp files.(The same issue happens when some cpp files are used only with flavour1, other cpp files are specific to flavour2).

I placed all cpp files in flavour1/cpp and expected it to do the job. However, what works for Java doesn't seem to work for cpp, as cmake always accepts files located in directory specified by CMAKE_HOME_DIRECTORY, i.e main/cpp and nothing else! Any other cpp files location produces error message:

Failed to activate protocol version: "CMAKE_HOME_DIRECTORY" is set but incompatible with configured source directory value.

The only work around, I can think of, is having different libraries for each product flavour. Is there a more natural approach?


Solution

  • I don't think you can entirely disable externalNativeBuild based on the build flavor. What you could do is pass an argument to CMake based on the build flavor and just don't build any libraries in the flavor that you want to exclude the native libs from:

    flavor1 {
        externalNativeBuild {
            cmake {
                arguments "-DENABLE_NATIVE_LIBS=TRUE"
            }
        }
    }
    
    flavor2 {
        externalNativeBuild {
            cmake {
                arguments "-DENABLE_NATIVE_LIBS=FALSE"
            }
        }
    }
    

    And then in your CMakeLists.txt:

    cmake_minimum_required(VERSION whatever you support)
    
    if (NOT ENABLE_NATIVE_LIBS)
        return()
    endif()
    
    # Rest of your CMakeLists.txt here.
    

    I haven't tested that, but it should work.