cmake does not find libraries when compiling for Android

I’ve just today discovered that its surprisingly simple to compile c++ projects with cmake for Android. I use Ubuntu Linux as a host, with the latest NDK. The build worked smoothly for a whole number of standard libraries (zlib, bzip2, Zstandard, and a few others)!

I’ve used the following parameters (I guess some of these are not even required, but I add them for completeness):

-GNinja
-DCMAKE_PREFIX_PATH=<TARGETDIR>/Debug;<TARGETDIR>/Debug/lib/cmake
-DCMAKE_INSTALL_PREFIX=<TARGETDIR>
-DCMAKE_BUILD_TYPE=Debug
-DCMAKE_CXX_STANDARD=20
-DCMAKE_FIND_PACKAGE_PREFER_CONFIG=ON
-DCMAKE_POLICY_DEFAULT_CMP0074=NEW
-DCMAKE_POLICY_DEFAULT_CMP0121=NEW
-DCMAKE_POLICY_DEFAULT_CMP0115=NEW
-DCMAKE_POLICY_DEFAULT_CMP0108=NEW
-DCMAKE_POLICY_DEFAULT_CMP0107=NEW
-DCMAKE_POLICY_DEFAULT_CMP0103=NEW
-DCMAKE_POLICY_DEFAULT_CMP0100=NEW
-DCMAKE_POLICY_DEFAULT_CMP0128=NEW
-DCMAKE_TOOLCHAIN_FILE=<NDKDIR>/22.1.7171670/build/cmake/android.toolchain.cmake
-DANDROID_NATIVE_API_LEVEL=30
-DANDROID_ABI=arm64-v8a

Now, while the build works, the find scripts from cmake seem not to work! Since the same build settings work on the host computer (just removing the Android specifics), I assume all paths etc should be correct.

For example, when building pcre2, it complains that bzip2 can not be found, even though its compiled and installed with cmake (including a package configuration). Similarly, when building Qt, it will not find bzip2, Zstandard and OpenSSL.

Is there something special needed when cross-compiling, or when building for Android?

I’m using cmake version 3.22.2-g45390d0 that I build from sources, and Ninja 1.10.2 also built from sources.

Ok, I’ve found the solution a few hours later. This should definitely be better documented, or maybe cmake could even help isolate the problem. The helpful discussion is in https://github.com/android/ndk/issues/912: The Android NDK cmake toolchain overrides CMAKE_FIND_ROOT_PATH.

I did not consider that there is such a variable that makes cmake essentially ignore CMAKE_PREFIX_PATH? I think it would be very helpful if cmake would warn when CMAKE_PREFIX_PATH points outside of CMAKE_FIND_ROOT_PATH.

Posting issue link for completeness https://gitlab.kitware.com/cmake/cmake/-/issues/17272#note_1159129

I am also facing same issue, how did you solve ?

@Praveen_CK , the solution for me was to put all paths from CMAKE_PREFIX_PATH also in CMAKE_FIND_ROOT_PATH, then it worked.

For me that boils down to something like:

cmake \
    "-DCMAKE_PREFIX_PATH=${TARGETDIR};${TOOLTARGETDIR};${EXTRASTARGETDIR}" \
    "-DCMAKE_FIND_ROOT_PATH=${TARGETDIR};${TOOLTARGETDIR};${EXTRASTARGETDIR}" \
    ...