'NDK Error "Unexpected native build target xyz. Valid targets are:"

I have an Android Studio project which depends on a native shared library. I have created a cmake file to compile the library and I have added a soft link to the shared library inside the android project (in src/main/jniLibs/armeabi). That way when the android project is built, the shared library is included in the package.

Here is the relevant part of build.gradle:

android {
    ...
    externalNativeBuild {
        cmake {
            path "../cpp/CMakeLists.txt"
        }
    }
}

The problem is that gradle tries to open the shared library before invoking the instructions to build it.

Information:Gradle tasks [:app:assembleDebug]
Error:Could not list contents of 'app/src/main/jniLibs/armeabi/libfoo.so'. Couldn't follow symbolic link.

How can I invoke the cmake from inside the project and include the library in the project at the same time?

--

EDIT

In the cmake the shared library is built with ExternalProject_Add. Unfortunately gradle doesn't see that target, nor does it see imported shared libraries as targets. So this does not work:

add_library(libfoo SHARED IMPORTED GLOBAL)
add_dependencies(libfoo libactual)

I tried to invoke building the particular target with a gradle config:

defaultConfig {
    ...
    externalNativeBuild {
        cmake {
            targets "libfoo"
        }
    }
}

But gradle still doesn't see it and fails with:

Unexpected native build target libfoo. Valid values are:

The valid values are basically an empty list.

Currently I work around this by creating a fictional executable depending on the library.

add_executable(libfoo a.c)
add_dependencies(libfoo libactual)


Solution 1:[1]

In my case, I added a new CMake target, but having none was cached somehow (by CMake or Gradle).

Simply close Android Studio, remove the entire build or .build directory, then open Android Studio and build again.

Note that sub-projects have their own separate build directory.

So, you may need to search for the word build, and after ensuring found result is not required, remove them too.


If still not fixed, remember that CMake has it's own separate cache files, which normallay are inside said directories unless you run CMake directly (outside of Android Studio).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1