Building OpenCV for Android and using it with the NDK - android

Context : I am currently developing an app on Android Studio for the Moverio BT 200 augmented reality glasses. I am using OpenCV, and specifically, the arUco module of the library. This module has to be used with the NDK. Also, it is not on the stable release, so I compiled the library myself (using this guide : https://zami0xzami.wordpress.com/2016/03/17/building-opencv-for-android-from-source/). The build of the library went well. After that, I made a android studio project (customOCVtest). I did it the way I always do when using OpenCV with Android Studio and the NDK, except this time it was with the custom build. I checked if the library was correctly loaded :
private static final String OCVdevTAG = "OCVmainAct";
static {
System.loadLibrary("native-lib");
if(!OpenCVLoader.initDebug()) {
Log.d(OCVdevTAG, "OpenCV not loaded");
} else {
Log.d(OCVdevTAG, "OpenCV loaded");
}
}
The library is indeed loaded when I build.
Now comes the problem : When I try to actually use the arUco module in my native code (here is my native-lib.cpp) :
#include <jni.h>
#include <string>
#include <opencv2/aruco.hpp>
extern "C" {
jstring
Java_com_jambonsama_customocvtest_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
cv::Ptr<cv::aruco::Dictionary> dict = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250);
cv::Mat marker;
cv::aruco::drawMarker(dict, 25, 200, marker, 1);
return env->NewStringUTF(hello.c_str());
}
}
the gradle sync works, but I can't build. I get the following error :
Error:FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:externalNativeBuildDebug'.
> Build command failed.
Error while executing 'C:\Users\JambonSama\AppData\Local\Android\Sdk\cmake\3.6.3155560\bin\cmake.exe' with arguments {--build C:\Users\JambonSama\AndroidStudioProjects\customOCVtest\app\.externalNativeBuild\cmake\debug\mips64 --target native-lib}
[1/1] Linking CXX shared library ..\..\..\..\build\intermediates\cmake\debug\obj\mips64\libnative-lib.so
FAILED: cmd.exe /C "cd . && C:\Users\JambonSama\AppData\Local\Android\sdk\ndk-bundle\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++.exe -target mips64el-none-linux-android -gcc-toolchain C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64 --sysroot=C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/platforms/android-21/arch-mips64 -fPIC -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -Wa,--noexecstack -Wformat -Werror=format-security -fno-exceptions -fno-rtti -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -Wa,--noexecstack -Wformat -Werror=format-security -fno-exceptions -fno-rtti -O0 -fno-limit-debug-info -O0 -fno-limit-debug-info -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--no-undefined -Wl,-z,noexecstack -Qunused-arguments -Wl,-z,relro -Wl,-z,now -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--no-undefined -Wl,-z,noexecstack -Qunused-arguments -Wl,-z,relro -Wl,-z,now -shared -Wl,-soname,libnative-lib.so -o ..\..\..\..\build\intermediates\cmake\debug\obj\mips64\libnative-lib.so CMakeFiles/native-lib.dir/src/main/cpp/native-lib.cpp.o C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_aruco.a -llog -lm "C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/sources/cxx-stl/gnu-libstdc++/4.9/libs/mips64/libgnustl_static.a" && cd ."
C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/mips64el-linux-android/4.9.x/../../../../mips64el-linux-android/bin\ld: C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a(alloc.cpp.o): Relocations in generic ELF (EM: 40)
C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/mips64el-linux-android/4.9.x/../../../../mips64el-linux-android/bin\ld: C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a(alloc.cpp.o): Relocations in generic ELF (EM: 40)
C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/mips64el-linux-android/4.9.x/../../../../mips64el-linux-android/bin\ld: C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a(alloc.cpp.o): Relocations in generic ELF (EM: 40)
C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/mips64el-linux-android/4.9.x/../../../../mips64el-linux-android/bin\ld: C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a(alloc.cpp.o): Relocations in generic ELF (EM: 40)
C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/mips64el-linux-android/4.9.x/../../../../mips64el-linux-android/bin\ld: C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a(alloc.cpp.o): Relocations in generic ELF (EM: 40)
C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/mips64el-linux-android/4.9.x/../../../../mips64el-linux-android/bin\ld: C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a(alloc.cpp.o): Relocations in generic ELF (EM: 40)
C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/mips64el-linux-android/4.9.x/../../../../mips64el-linux-android/bin\ld: C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a(alloc.cpp.o): Relocations in generic ELF (EM: 40)
C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/mips64el-linux-android/4.9.x/../../../../mips64el-linux-android/bin\ld: C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a(alloc.cpp.o): Relocations in generic ELF (EM: 40)
C:/Users/JambonSama/AppData/Local/Android/sdk/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/mips64el-linux-android/4.9.x/../../../../mips64el-linux-android/bin\ld: C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a(alloc.cpp.o): Relocations in generic ELF (EM: 40)
C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a: error adding symbols: File in wrong format
clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
In particular, this error message tells me that I tried to build with the following argument :
{--build C:\Users\JambonSama\AndroidStudioProjects\customOCVtest\app\.externalNativeBuild\cmake\debug\mips64 --target native-lib}
This argument is automatically generated by AS, and I can't find the file where it is passed. I believe that if I can find it, I can build for arm (which is what I want), instead of mips. The thing is, I can't find it. (And I'm not even sure that is indeed what I'm looking for. I'm just trying to make my project build for my glasses.)
Here after is my CMakeLists.txt :
# Sets the minimum version of CMake required to build the native
# library. You should either keep the default value or only pass a
# value of 3.4.0 or lower.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds it for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
# Associated headers in the same location as their source
# file are automatically included.
src/main/cpp/native-lib.cpp )
include_directories(C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/jni/include)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because system libraries are included in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in the
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
native-lib
C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_core.a
C:/Libs/opencv_src/opencv/platforms/build_android_arm/install/sdk/native/libs/armeabi-v7a/libopencv_aruco.a
# Links the target library to the log library
# included in the NDK.
${log-lib} )
here is my app build.gradle :
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.jambonsama.customocvtest"
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
sourceSets { main { jni.srcDirs = ['src/main/jni', 'src/main/jniLibs/'] } }
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.1'
testCompile 'junit:junit:4.12'
compile project(':openCVLibrary310dev')
}
and my openCVLibrary310dev build.gradle
apply plugin: 'com.android.library'
android {
compileSdkVersion 25
buildToolsVersion "23.0.2"
defaultConfig {
ndk {
abiFilter("armeabi-v7a")
}
minSdkVersion 14
targetSdkVersion 25
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
What I tried, mainly by just copying stuff that helped other people solve problems that seemed similar to mines :
#set(CMAKE_SYSTEM_NAME Android)
or
#set(CMAKE_TOOLCHAIN_FILE "Toolchain file" CACHE FILEPATH "C:/Libs/opencv_src/opencv/platforms/android.toolchain.cmake")
or
#set( CMAKE_CXX_COMPILER "C:/Libs/android-ndk-r13b/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64/bin/arm-linux-androideabi-g++.exe" )
in the CMakeLists.txt
and
splits {
abi {
enable true
reset()
include 'armeabi-v7a'
universalApk true
}
}
or
tasks.getByPath(":app:linkMipsDebugRemoteDesktopSharedLibrary").enabled = false
in the build.gradle (I tried both because I didn't know which one was supposed to have it).
Except for the very last bit of code (the task.getByPath...), the sync worked, but I couldn't build. For the last one, I couldn't even sync.
I also tried to rebuild the library for mips, since the architecture seems to be the problem, but I have no idea how to do that.
Where can I find the file where the following argument :
{--build C:\Users\JambonSama\AndroidStudioProjects\customOCVtest\app\.externalNativeBuild\cmake\debug\mips64 --target native-lib}
is passed when building? And / or how do I make Android Studio build my project for arm architecture?

So the mips architecture problem can be solved by adding the following code to the gradle.build of app, at the end of the android block :
productFlavors {
armv7 {
ndk {
abiFilter "armeabi-v7a"
}
}
fat
}
But then, other problems arised. Notably, the library is built with the carotene options, which Android Studio doesn't like, and then, the gzlib misses, so Android Studio can't build and / or run. So after MANY trials, I finally achieved what I wanted : cross-compilation of openCV with extra modules for Android on Windows, and building an AS project with said built library so that it works. I documented my whole proccess, from downloading the openCV sources up until running my application on my arm-architected device, I'll just copy paste it here for anyone who needs to do that too. The following instructions are mainly based on this tutorial (thank you to Zamrath Nizam who wrote it). The only problem with that tutorial is that it's probably a little old, so some options / steps need to be altered.
CROSS COMPILE OPENCV FROM SOURCE WITH EXTRA MODULES FOR ANDROID FROM WINDOWS10
* FIRST : prerequisites *
download OpenCV and unzip (say at '../opencv-source')
download OpenCV extra modules and unzip (say at '../opencv-contrib-source')
download Android NDK (say at '../ndk-dir')
download CMake (to say '../cmake-dir') and MinGW (to say '../mingw-dir')
install Android Studio
* SECOND : configure with CMake *
go to '../opencv-source/platforms' and create a folder named 'build_android_arm'
in CMake, fill the following first two fields with the following paths :
where is the source code : '../opencv-source'
where to build the binaries : '../opencv-source/platforms/build_android_arm'
add the following options via the 'Add Entry' :
ANDROID_NDK, type 'path', value '../ndk-dir'
ANDROID_NDK_HOST_X64, type 'bool', value 1
CMAKE_TOOLCHAIN_FILE, type 'path', value '../opencv-source/platforms/android/android.toolchain.cmake'
press 'Configure'
choose 'MinGW Makefiles' as the compiler
choose 'Specify toolchain file for cross-compiling'
press 'Next', and 'Finish'
note 1 : As long as you've got no error message, everything's good. Don't worry about the warning messages (like CMake telling you you're doing deprecated stuff).
note 2 : If you can't configure at that step, try to read the next few points, it might help.
change the following additional options via the 'Search' field :
EXTRA_MODULE_PATH, type 'path', value '../opencv-contrib-source/modules'
WITH_CAROTENE, type 'bool', value 0
BUILD_ZLIB, type 'bool', value 1
note : You MUST have configured already once before this step, because the variables created before are regrouped under the group 'Ungrouped entries', while the following variables are CMake automatically generated variables, and NEED to be grouped in the right groups (which is NOT 'Ungrouped entries').
verify that the following options are correctly set up (via the 'Search' field) :
ANDROID_NDK_HOST_X64, type 'bool', value 1
CMAKE_MAKE_PROGRAM, type 'path', value '../mingw-dir/bin/mingw32-make.exe'. This option, I actually DIDN'T have it in my CMake config. IF when you press 'Configure', it doesn't work AND you don't have this option, then you should try adding it (but I don't know how). IF when you press 'Configure' you don't have any problem, don't bother about that variable. This check comes from the original tutorial linked above.
CMAKE_TOOLCHAIN_FILE, type 'path', value '../opencv-source/platforms/android/android.toolchain.cmake'
press 'Configure'
choose 'MinGW Makefiles' as the compiler
choose 'Specify toolchain file for cross-compiling'
press 'Next', and 'Finish'
press 'Generate'
* THIRD : compile with mingw *
go to '../mingw-dir/msys/1.0' and run 'msys' bash file
navigate to '../opencv-source/platforms/android_arm'
run 'mingw32-make' command
run 'mingw32-make install' command
* FOURTH : android project *
launch Android Studio and create a new project :
select File -> New -> New Project...
fill the 'Application name' with let's say 'cOCV'
check the 'Include C++ Support' box
click 'Next'
choose your min SDK (let's say API 14: Android 4.0 (IceCreamSandwich)
click 'Next', 'Next' and 'Finish'
go to File -> New -> Import Module...
provide '../opencv-source/platforms/android_arm/install/sdk/java'
click 'Next' and 'Finish'
change the targets in build.gradle file in openCVLibraryXXX (imported module) folder :
compileSdkVersion and targetSdkVersion should be the same, greater or equal to 23
minSdkVersioon should be the same as the one specified when creating the project
in the build.gradle file in openCVLibraryXXX (imported module) folder :
replace 'apply plugin: com.android.application' as, 'apply plugin: com.android.library'
remove the line 'applicationId "org.opencv"'
note : That last step is done in order to avoid following error : 'unspecified on project app resolves to an APK archive which is not supported as a compilation dependency'.
add the imported library as a dependency to the 'app' module in File->'Project Structure'
create a jniLibs folder in 'app/src/main' :
right click 'app' in the Android view on the left menu
click 'New-Folder-JNI Folder'
check the 'Change Folder Location'
set the 'Target Source Set as 'app/src/main/jniLibs'
copy libraries of OpenCV from 'opencv-source/platforms/android_arm/install/sdk/native/libs'
into the newly created folder (jniLibs) inside the
'AndroidStudioProjects/cOCV/app/src/main/jniLibs' folder
note : For example, my AndroidStudioProjects folder is located at 'C:\Users\JambonSama\AndroidStudioProjects'.
in 'opencv-contrib-source/modules/module_you_desperately_need/CMakeLists.txt', change 'ocv_define_module(module_you_desperately_need opencv some other modules)' for 'ocv_define_module(module_you_desperately_need opencv some other modules WRAP java)'
note 1 : THIS STEP MAY BE USELESS, because WRAP java is probably already written in the file.
note 2 : If 'python' is written too, it's fine, you let it be written where it is.
in CMakeLists.txt, add :
the following two lines after the 'add_library' block and before the 'find_library' block :
include_directories(../opencv_src/opencv/platforms/build_android_armn/install/sdk/native/jni/include)
link_directories(../AndroidStudioProjects/cOCVn/app/src/main/jniLibs/armeabi-v7a)
note : These two lines pretty straight-forwardly give the paths for the include and link directories
the following lines after the 'find_library' block and before the 'target_link_libraries' block :
file(GLOB PARTYLIBS "../opencv_src/opencv/platforms/build_android_armn/install/sdk/native/3rdparty/libs/armeabi-v7a/*.a")
file(GLOB CVLIBS "../opencv_src/opencv/platforms/build_android_armn/install/sdk/native/libs/armeabi-v7a/*.a")
note : These are for easier linking commands, see next point.
the following paths, AS WRITTEN, in the 'target_link_libraries', after the 'native-lib' variable, and before the '${log-lib}' one :
${CVLIBS}
${PARTYLIBS}
${CVLIBS}
note : THAT IS THE TRICKY PART : because of cyclical dependencies, you have to write CVLIBS, PARTYLIBS, and then CVLIBS a second time, otherwise you won't stop having linking errors. By now, everything should be linked.
in the gradle.build of app, add the following code :
productFlavors {
armv7 {
ndk {
abiFilter "armeabi-v7a"
}
}
fat
}
at the end of the android block
note : This prevents the mips64 architecture error at build, by specifying once and for all the arm architecture
in the native-lib.cpp :
try the following code in the 'stringFromJNI' function (this one is automatically generated by AS when the project is created)
cv::Mat test;
cv::VideoCapture camera;
camera.open(0);
cv::Ptrcv::aruco::Dictionary dict = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250);
cv::Mat marker;
cv::aruco::drawMarker(dict, 25, 200, marker, 1);
std::string hello = "Hello from C++";
return env-NewStringUTF(hello.c_str());
don't forget the following includes :
#include jni.h
#include string
#include opencv2/aruco.hpp
#include opencv2/videoio.hpp
note : Because the string is not generated before the end of the function, you know, when you test, that if the string is indeed displayed on screen, the function has been gone through without problem, and that you're good (since the above provided code use some modules that are not on the stable realease as of 08/12/2016 (8th of december, I write dates with a dd/mm/yyyy format).
time to test :
sync the gradle
build
run on an arm device
You're good to go \ o \\ O // o /
Additional notes :
All the gradle.build files and the CMakeLists.txt file can be easily found on the Android View in the menu on the left of the window in AS.
Remember if you've got errors navigating in the command window that maybe your '/' should be '\' or the other way round. ('cd' command to navigate in a command window).
I run on Windows10.
If you're not quite sure what you should see on screen steps by steps, the tutorial I mentioned at the beginning of the answer should give you a good idea what you're supposed to see up until the AS project creation. Then, you can give a look at this tutorial, which explains how to setup OpenCV SDK in Android Studio project FOR THE OFFICIAL RELEASE. The steps I provided differs from BOTH those tutorials, but I put them here, because they can help you know what your screen / windows should look like.

Related

Will cmake compiled TFLite work on android?

I'm making a project with 2 variations, a desktop version and an android version. Both of them are using the same c++ code base. I want to use TFLite without getting into any android configuration like gradle or an aar file. I just want a pure .so file that my c++ can use thus android can through ndk. I know there are some complications like ndk using clang and requiring arm64 architecture, but I think it should be possible. Note that my project requires ndk version 22 and above.
Here is how I configured tflite for my desktop/debian project:
On ~/Desktop/ I ran git clone https://github.com/tensorflow/tensorflow.git tensorflow_src
mkdir tflite_build & cd ~/Desktop/tflite_build
cmake ../tensorflow_src/tensorflow/lite
cmake --build . I've removed the -J flag regardless of what the docs says because it causes my pc to freeze.
mkdir ~/Desktop/tf_test & cd ~/Desktop/tf_test
Create a CMakeLists.txt and a main.cpp file inside tf_testdirectory.
Put the main code from the minimal example on the github repo provided above then this code in CMake:
cmake_minimum_required(VERSION 3.16)
project(minimal C CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DTFLITE_DISABLE_TELEMETRY=1")
set(TENSORFLOW_SOURCE_DIR "" CACHE PATH
"Directory that contains the TensorFlow project" )
if(NOT TENSORFLOW_SOURCE_DIR)
get_filename_component(TENSORFLOW_SOURCE_DIR
"/home/user/Desktop/tensorflow_src" ABSOLUTE)
endif()
add_subdirectory(
"${TENSORFLOW_SOURCE_DIR}/tensorflow/lite"
"${CMAKE_CURRENT_BINARY_DIR}/tensorflow-lite" EXCLUDE_FROM_ALL)
add_executable(minimal minimal.cc)
target_link_libraries(minimal tensorflow-lite)
Created the folder tf_Test/build and ran cmake .. inside it.
After cmake is completed I run make inside the build directory
This works just fine on debian. However when I try to add this to my cmake on my android ndk project, connect my tablet and run the project I get all these errors:
...
- Looking for strtoull_l - found
-- Using toolchain file: /home/user/Android/Sdk/ndk/25.0.8775105/build/cmake/android.toolchain.cmake.
-- CMAKE_CXX_FLAGS: -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -frtti -fexceptions -fvisibility=hidden -std=c++17 -O0 -Wall -Wextra -Wshadow -Wnon-virtual-dtor -pthread -frtti -fexceptions
-- Found Python3: /usr/bin/python3.9 (found suitable version "3.9.2", minimum required is "3.5") found components: Interpreter
-- Downloading pthreadpool to /home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/pthreadpool-source (define PTHREADPOOL_SOURCE_DIR to avoid it)
-- Configuring incomplete, errors occurred!
See also "/home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/pthreadpool-download/CMakeFiles/CMakeOutput.log".
-- The ASM compiler identification is Clang with GNU-like command-line
-- Found assembler: /home/user/Android/Sdk/ndk/25.0.8775105/toolchains/llvm/prebuilt/linux-x86_64/bin/clang
-- Downloading FP16 to /home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/FP16-source (define FP16_SOURCE_DIR to avoid it)
-- Configuring incomplete, errors occurred!
See also "/home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/FP16-download/CMakeFiles/CMakeOutput.log".
-- Downloading FXdiv to /home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/FXdiv-source (define FXDIV_SOURCE_DIR to avoid it)
-- Configuring incomplete, errors occurred!
See also "/home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/FXdiv-download/CMakeFiles/CMakeOutput.log".
-- RUY is enabled.
-- Configuring incomplete, errors occurred!
See also "/home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/CMakeFiles/CMakeOutput.log".
See also "/home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/CMakeFiles/CMakeError.log".
CMake Warning at /home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/abseil-cpp/CMakeLists.txt:70 (message):
A future Abseil release will default ABSL_PROPAGATE_CXX_STD to ON for CMake
3.8 and up. We recommend enabling this option to ensure your project still
builds correctly.
CMake Error: CMake was unable to find a build program corresponding to "Ninja". CMAKE_MAKE_PROGRAM is not set. You probably need to select a different build tool.
No such file or directory
CMake Error: Generator: execution of make failed. Make command was: &&
CMake Error at /home/user/Desktop/official_stuff/tensorflow_src/tensorflow/lite/CMakeLists.txt:167 (add_subdirectory):
add_subdirectory given source
"/home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/pthreadpool-source"
which is not an existing directory.
CMake Error: CMake was unable to find a build program corresponding to "Ninja". CMAKE_MAKE_PROGRAM is not set. You probably need to select a different build tool.
No such file or directory
CMake Error: Generator: execution of make failed. Make command was: &&
CMake Error: CMake was unable to find a build program corresponding to "Ninja". CMAKE_MAKE_PROGRAM is not set. You probably need to select a different build tool.
No such file or directory
CMake Error: Generator: execution of make failed. Make command was: &&
CMake Error at /home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/xnnpack/CMakeLists.txt:844 (ADD_SUBDIRECTORY):
ADD_SUBDIRECTORY given source
"/home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/pthreadpool-source"
which is not an existing directory.
CMake Error at /home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/xnnpack/CMakeLists.txt:884 (ADD_SUBDIRECTORY):
ADD_SUBDIRECTORY given source
"/home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/FXdiv-source"
which is not an existing directory.
CMake Error at /home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/xnnpack/CMakeLists.txt:908 (ADD_SUBDIRECTORY):
ADD_SUBDIRECTORY given source
"/home/user/Desktop/native/examples/android/app/.cxx/Debug/5c1w1z3w/arm64-v8a/FP16-source"
which is not an existing directory.
What's the right way to approach this? Following the android build documentation on tflite's website causes a lot of problems.
Update:
Installing ninja fixed almost all my problems, the only error I have now is:
In file included from /home/user/Desktop/official_stuff/tensorflow_src/tensorflow/lite/python/interpreter_wrapper/python_error_reporter.cc:16:
/home/user/Desktop/official_stuff/tensorflow_src/tensorflow/lite/python/interpreter_wrapper/python_error_reporter.h:19:10: fatal error: 'Python.h' file not found
python3 is in fact installed on my system, I used it on a c code before.
Update: Adding this to top of my cmake solved the python issue:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/include/python3.9 -I/usr/include/python3.9 -Wno-unused-result -Wsign-compare -g -ffile-prefix-map=/build/python3.9-RNBry6/python3.9-3.9.2=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector -Wformat -Werror=format-security -DNDEBUG -g -fwrapv -Wall")
Update:
Now I get:
In file included from /home/user/Desktop/SmartAlpha/official_stuff/tensorflow_src/tensorflow/lite/python/interpreter_wrapper/numpy.cc:17:
In file included from /home/user/Desktop/SmartAlpha/official_stuff/tensorflow_src/tensorflow/lite/python/interpreter_wrapper/numpy.h:49:
In file included from /usr/include/python3.9/Python.h:8:
/usr/include/python3.9/pyconfig.h:9:12: fatal error: 'aarch64-linux-gnu/python3.9/pyconfig.h' file not found
LAST EDIT: You seem to completely overlook what I'm trying to explain you the whole time about different architectures. Your phone is not running on the same cpu architecture as your desktop. Your desktop machine is most likely running on amd64, while your phone is most likely arm64 which is also known as Aarch64 (do you now see what the latest error means? - It can't find the appropriate packages for the correct architecture - you can see that from the path in the error message).
You installed the amd64 package by issuing sudo apt-get install python-dev not the arm64 package. Check this official debian wiki on how to use MultiArch packages
You need to:
Update your system so that it can download the packages for different architectures
And sudo apt-get install python-dev:arm64
EDIT: Regarding the error in the updated question, you are most likely missing python development packages. Since you are on Debian I've looked for a possible package of interested and this might be it:
python-dev, try to apt-get it for the correct architecture that you need and maybe it will resolve your issues.
Make sure that Ninja is installed. CMake is trying to use it - this confuses a lot of users as they most commonly use Makefiles and don't know that an alternative exists. I don't see you explicitly stating that you use CMake + Ninja and hence I mention it.
If you have Ninja installed then the issue is most likely caused by the fact that it can't resolve the path via just the executable name. Take a look at CMAKE_MAKE_PROGRAM to better understand what I mean.
If 2. is your issue then you can try and set the whole path to this CMAKE_MAKE_PROGRAM variable, i.e. set(CMAKE_MAKE_PROGRAM /absolute/path/to/bin/ninja) and see if resolves the issue.

How to build libpng NDK CMake android? [duplicate]

I'm trying to start a native app project with Android Studio and CMake on Windows 10, but I'm stuck at including libpng.
For starters it's the first time I've seen a CMakeLists.txt file. It took me a day to figure out target_link_libraries(native-activity ... png) could not be target_link_libraries(png native-activity ...) since all the error messages were about files not being created and commands failing due to missing requirements from the toolchain (why were the essential errors at the end of the list? not cool!).
After finally managing to include libpng in the project I now get a build error:
Error:Execution failed for task ':app:externalNativeBuildDebug'.
...
error: unknown target CPU 'armv5te'
CMake Error at scripts/genout.cmake:78 (message):
Failed to generate
C:/APP_PATH/app/libpng-1.6.28/build/scripts/symbols.out.tf1
ninja: build stopped: subcommand failed.
I've recursively grep'ed my project, .android, .AndroidStudio2.2 directories, as well as filenames, and found absolutely nothing with armv5te except for the genout.cmake. My abiFilters line is abiFilters 'x86'.
How do I build libpng to link to my native app? Also, in Android Studio it shows the project now includes the libpng source files (with no less than 9 projects dedicated to it!). Is there any way to remove it?
Here is my CMakeLists.txt:
cmake_minimum_required(VERSION 3.4.1)
# build native_app_glue as a static lib
add_library(app-glue STATIC ${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c)
set(png_src_dir ../../../../libpng-1.6.28)
set(PNG_STATIC ON)
add_subdirectory(${png_src_dir} ${png_src_dir}/build)
# now build app's shared lib
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++14")
add_library(native-activity SHARED
main.cpp logger.cpp logger.h game.cpp game.h
shaders.cpp shaders.h assets.cpp assets.h)
target_include_directories(native-activity PRIVATE ${ANDROID_NDK}/sources/android/native_app_glue
C:/devlibs/include
${png_src_dir})
# add lib dependencies
target_link_libraries(native-activity app-glue android log EGL GLESv2 png)
I've managed libpng to work with android NDK app (CMake build system instead of Android.mk) as static library. I used libpng-android repackaging. Here are things I've done:
git clone https://github.com/julienr/libpng-android.git into ${YOUR_LIBS_FOLDER} (I used ${ANDROID_NDK_ROOT_DIRECTORY}/sources/android).
Add ${ANDROID_NDK_ROOT_DIRECTORY} (home/username/Android/sdk/ndk-bundle for me) to global $PATH variable which is needed for build script).
Build lib with ndk-build (there is ./build.sh for that in directory with lib). Library will be built for different ABI targets ( arm64-v8a, armeabi, x86_64 etc).
At this point you have library headers at ${YOUR_LIBS_FOLDER}/libpng-android/jni and libpng.a at ${YOUR_LIBS_FOLDER}/libpng-android/obj/local/${ANDROID_ABI}/, where ${ANDROID_ABI} is target platform.
Finally you could include lib at CMakeLists.txt. libpng requires zlib compression library so you need to link against it aswell (zlib is provided by android studio so just add -lz flag).
Here is related piece from my CMakeLists.txt:
add_library(libpng STATIC IMPORTED)
set_target_properties(libpng PROPERTIES IMPORTED_LOCATION
${YOUR_LIBS_FOLDER}/libpng-android/obj/local/${ANDROID_ABI}/libpng.a)
add_library(appManager SHARED src/main/cpp/appManager.cpp)
target_include_directories(appManager PRIVATE ${YOUR_LIBS_FOLDER}/libpng-android/jni/)
target_link_libraries(appManager
android
libpng
z)
Few things to note there:
${ANDROID_ABI} is a variable set by Android Studio build system.
Once again: you need to link against zlib, that is why we have libpng z instead of libpng in target_link_libraries.
With Android Studio 3.6, including libpng into your project is rather easy.
Download the latest sources from sourceforge and unpack the zip file.
In Android Studio, make sure you have NDK and CMake installed (in SDK Manager)
Create a new Android Library module, call it pngAndroid (I would recommend
to set the Package Name to org.libpng.libpng, same as MacOS). Keep it Java, and choose the min SDK that fits your app.
For this module, choose File/Link C++ Project with Gradle. Find CMakleLists.txt of libpng that you downloaded as step 1.
In the pngAndroid's build.gradle, add
android.defaultConfig.externalNativeBuild.cmake.targets "png_static"
In Project Structure dialog, specify module dependency between your Module and pngAndroid.
When you build the pngAndroid Module, you will see files libpng16d.a in build/intermediates/cmake/debug/obj directory under pngAndroid.
In your Module, you also have CMakleLists.txt. In this script, you have a target, e.g.
add_library(native-library SHARED …
You should add libpng as dependency of native-library:
target_link_libraries(native-library libpng)
Elsewhere in this CMakleLists.txt you should define the imported libpng:
add_library(libpng STATIC IMPORTED)
set_target_properties(libpng PROPERTIES IMPORTED_LOCATION
../pngAndroid/build/intermediates/cmake/debug/obj/${ANDROID_ABI}/libpng16d.a)
set_target_properties(libpng PROPERTIES INTERFACE_INCLUDE_DIRECTORIES
../../lpng1637)
set_target_properties(libpng PROPERTIES IMPORTED_LINK_INTERFACE_LIBRARIES
z)
Note that here I used relative paths a) to the pngAndroid Module that you added to your Android Studio project, and b) to the libpng sources that you downloaded. In your setup, the relative paths may be different.
For completeness, here is a cleaned-up build.gradle script for pngAndroid to build shared library libpng16d.so:
apply plugin: 'com.android.library'
android {
compileSdkVersion 29
defaultConfig {
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
externalNativeBuild {
cmake {
arguments "-DSKIP_INSTALL_ALL=YES"
targets "png"
}
}
}
externalNativeBuild {
cmake {
path file('../../lpng1637/CMakeLists.txt')
}
}
}
When you build the module, you get in build/outputs an aar file that contains the jni directory with armeabi-v7a/libpng16d.so and all other ABI variants.
Last, it's worth mentioning that Google is working on an easier native package manager. Unfortunately, it's still not released.

Linking external libraries using NDK, Gradle & CMake in Android Studio

I've come back to Android development after a gap and my old ANT based build chain no longer seem to function (that's a separate issue) with the latest SDK, so I'm trying to do things the new way, which is based around gradle and CMake.
I have a number of pre-built static and dynamic 3rd party libraries that my project needs but I've been unable to link these successfully.
From what I can gather, these need to be specified in the 'CMakeLists.txt' file rather than the 'build.gradle' files but I'm new to both systems, so please correct me if I'm wrong.
Here's what I've tried so far:
first, I try to resolve the location of bullet. I've tried variants where I omit the 'lib' the '.a' and the 'armeabi-v7a' (hoping it'd pick up the right CPU variant) but none have worked
find_library(bullet_lib libBullet.a HINTS ${LIBBASE}bullet3/build3/Android/obj/local/armeabi-v7a)
I'm not sure how this differs from the libraries included in target_link_libraries
add_library(bullet_lib STATIC IMPORTED)
this finds the built-in libraries fine but I get linker errors for 'bullet' and other 3rd party libs
target_link_libraries(my_project_name android log EGL GLESv2 bullet_lib)
${LIBBASE} is the base dir for the 3rd party libraries and seems to be OK but, here's another thing: CMake errors don't seem to appear in android studio! I can sort of work out where it's having problems by running cmake . in the folder that contains the 'CMakeLists.txt' file but I'm not quite sure I'm calling that with the correct parameters: whatever Android Studio does with cmake and that file are a black box to me at this time.
The only messages I can see in android studio are linker errors (it doesn't mention CMake errors about not finding the libraries, which is the cause of these linker errors:)
Build command failed.
Error while executing process E:\prog\Android\cmake\3.6.4111459\bin\cmake.exe with arguments {--build E:\prog\anthracite\gradle\AnthracitePlayerAPI21\app\.externalNativeBuild\cmake\debug\x86_64 --target anthracite-lib}
[1/1] Linking CXX shared library ..\..\..\..\build\intermediates\cmake\debug\obj\x86_64\libanthracite-lib.so
FAILED: cmd.exe /C "cd . && E:\prog\Android\ndk-bundle\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++.exe --target=x86_64-none-linux-android --gcc-toolchain=E:/prog/Android/ndk-bundle/toolchains/x86_64-4.9/prebuilt/windows-x86_64 --sysroot=E:/prog/Android/ndk-bundle/sysroot -fPIC -isystem E:/prog/Android/ndk-bundle/sysroot/usr/include/x86_64-linux-android -D__ANDROID_API__=21 -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -Wa,--noexecstack -Wformat -Werror=format-security -std=c++11 -fexceptions -O0 -fno-limit-debug-info -Wl,--exclude-libs,libgcc.a -Wl,--exclude-libs,libatomic.a --sysroot E:/prog/Android/ndk-bundle/platforms/android-21/arch-x86_64 -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--no-undefined -Wl,-z,noexecstack -Qunused-arguments -Wl,-z,relro -Wl,-z,now -shared -Wl,-soname,libanthracite-lib.so -o ..\..\..\..\build\intermediates\cmake\debug\obj\x86_64\libanthracite-lib.so #CMakeFiles/anthracite-lib.rsp && cd ."
E:\prog\anthracite\src/CCmpPhysicsScene3D.cpp:237: error: undefined reference to 'btDbvtBroadphase::btDbvtBroadphase(btOverlappingPairCache*)'
E:\prog\anthracite\src/CCmpPhysicsScene3D.cpp:240: error: undefined reference to 'btDefaultCollisionConfiguration::btDefaultCollisionConfiguration(btDefaultCollisionConstructionInfo const&)'
E:\prog\anthracite\src/CCmpPhysicsScene3D.cpp:242: error: undefined reference to 'btCollisionDispatcher::btCollisionDispatcher(btCollisionConfiguration*)'
E:\prog\anthracite\src/CCmpPhysicsScene3D.cpp:243: error: undefined reference to 'btSequentialImpulseConstraintSolver::btSequentialImpulseConstraintSolver()'
E:\prog\anthracite\src/CCmpPhysicsScene3D.cpp:246: error: undefined reference to 'btDefaultSoftBodySolver::btDefaultSoftBodySolver()'
E:\prog\anthracite\src/CCmpPhysicsScene3D.cpp:247: error: undefined reference to 'btSoftRigidDynamicsWorld::btSoftRigidDynamicsWorld(btDispatcher*, btBroadphaseInterface*, btConstraintSolver*, btCollisionConfiguration*, btSoftBodySolver*)'
E:\prog\anthracite\src/CCmpPhysicsScene3D.cpp:250: error: undefined reference to 'btDiscreteDynamicsWorld::btDiscreteDynamicsWorld(btDispatcher*, btBroadphaseInterface*, btConstraintSolver*, btCollisionConfiguration*)'
E:\prog\anthracite\src/CCmpPhysJointHinge.cpp:117: error: undefined reference to 'btHingeConstraint::btHingeConstraint(btRigidBody&, btVector3 const&, btVector3 const&, bool)'
clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
And running 'cmake .' from the command line gives:
-- Selecting Windows SDK version 10.0.16299.0 to target Windows 10.0.17133.
CMake Warning at CMakeLists.txt:447 (message):
resolved libraries:
CMake Warning at CMakeLists.txt:448 (message):
e:/prog/libs/bullet3/build3/Android/obj/local/armeabi-v7a
CMake Warning at CMakeLists.txt:449 (message):
bullet_lib-NOTFOUND
-- Configuring done
-- Generating done
-- Build files have been written to: E:/prog/anthracite/gradle/AnthracitePlayerAPI21/app
although, as I mentioned above, I'm not sure of the veracity of that output as the calling parameters to 'cmake' are likely to be quite different from inside Android Studio. (e.g it's defaulting to a windows build, so I'm not sure if it'd look for '.lib' libraries rather than '.a' or '.so')
Also, I'm using these lines in my 'CMakeLists.txt' file to report the status of the build:
message(WARNING "resolved libraries:")
message(WARNING ${LIBBASE}bullet3/build3/Android/obj/local/armeabi-v7a)
message(WARNING ${bullet_lib})
Anyway, I'm clearly missing something and I've not been able to find any clear guides regarding this. It seems a really simple and obvious thing to do (link a library) but it seems to be a massive pain.
I'd be grateful for any pointers.
You must take care of ABI incompatibility. You are building libanthracite-lib.so for x86_64, so you need the same variant of libBullet.a. If you only need armeabi-v7a, you must specify this in build.gradle, e.g.
android {
externalNativeBuild {
cmake {
path 'CMakeLists.txt'
}
}
defaultConfig {
ndk {
abiFilters 'armeabi-v7a'
}
externalNativeBuild {
cmake {
arguments '-DCMAKE_VERBOSE_MAKEFILE=ON'
}
}
}
}
In your E:\prog\anthracite\gradle\AnthracitePlayerAPI21\app\CMakeLists.txt
add_library(bullet_lib STATIC IMPORTED)
set_target_properties(bullet_lib PROPERTIES IMPORTED_LOCATION
${LIBBASE}/bullet3/build3/Android/obj/local/${ANDROID_ABI}/libBullet.a)
target_link_libraries(my_project_name bullet_lib android log EGL GLESv2)
The order of libraries in target_link_libraries may be important, so keep static libs on the left.
I guess you build libBullet.a with ndk-build. You can create a separate library module (let's call in bullet_module) to your AS Project, even if it has no Java files, and point it to the Android.mk:
apply plugin: 'com.android.library'
android {
compileSdkVersion 27
defaultConfig {
ndk {
abiFilters 'armeabi-v7a'
}
externalNativeBuild {
ndkBuild {
targets 'Bullet'
}
}
}
externalNativeBuild {
ndkBuild {
path "${LIBBASE}/bullet3/build3/Android/jni/Android.mk"
}
}
}
Now you can change your CMakeLists.txt to look at results of bullet_module build:
set_target_properties(bullet_lib PROPERTIES IMPORTED_LOCATION
<path/to/bullet_module>/build/intermediates/ndkBuild/debug/obj/local/${ANDROID_ABI}/libBullet.a)

needed by '../../../../build/intermediates/cmake/debug/obj/armeabi-v7a/libnative-lib.so', missing and no known rule to make it

I want to implement AEs and RSA in my project.i downloaded pre built openssl and included in my project. After including openssl in my project i am getting error as above mentioned.i searched on SO some answers mentioned to include set_target_properties in CMake(U can check my cmake below) but still no use.
My CMakeLists.txt
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/native-lib.cpp )
add_library(openssl SHARED IMPORTED)
set_target_properties (openssl PROPERTIES IMPORTED_LOCATION ${PROJECT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/lib/libcrypto.so )
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
include_directories(jni/include/)
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
native-lib
${CMAKE_CURRENT_SOURCE_DIR}/jniLibs/${ANDROID_ABI}/lib/libcrypto.a
${CMAKE_CURRENT_SOURCE_DIR}/jniLibs/${ANDROID_ABI}/lib/libssl.a
# Links the target library to the log library
# included in the NDK.
${log-lib} )
and My build.graddle is here
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.manvish.prebuiltcrypto"
minSdkVersion 14
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ""
abiFilters "x86_64", "armeabi-v7a"
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
help me to resolve this issue?
The complete error log is here
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:externalNativeBuildDebug'.
> Build command failed.
Error while executing process /home/manvish/Android/Sdk/cmake/3.6.4111459/bin/cmake with arguments {--build /home/manvish/Gajanand/PrebuiltCrypto/app/.externalNativeBuild/cmake/debug/armeabi-v7a --target native-lib}
ninja: error: '../../../../jniLibs/armeabi-v7a/lib/libcrypto.a', needed by '../../../../build/intermediates/cmake/debug/obj/armeabi-v7a/libnative-lib.so', missing and no known rule to make it
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
I can guess that you get the cited error because you don't have jniLibs/x86_64/lib/libcrypto.a. Try to use
abiFilters "x86", "armeabi-v7a"
This error happend to me when upgrade targetSDKversion from 21 to 27. The last change of this horrible stage of my life as a Android programmer was this error:
What went wrong:
Execution failed for task ':myProject:externalNativeBuildDebug'.
Build command failed.
Error while executing process C:\Users\myUser\AppData\Local\Android\Sdk\cmake\3.6.4111459\bin\cmake.exe with arguments {--build D:\workspaces\android\myProject.externalNativeBuild\cmake\debug\armeabi-v7a --target myProject}
ninja: error: '../../../../src/main/libs/armeabi-v7a/libcrypto.so', needed by '../../../../build/intermediates/cmake/debug/obj/armeabi-v7a/libmyProject.so', missing and no known rule to make it
My app uses a own .so which uses funcions of libcrypto.so inside him, for that reason appers myproject.so
Change the old path for the new one, for that, you need to go to External Build Files/CMakeLists.txt in Android Studio (if dont appers in your Android Studio interface, go to your FileSystem and search it inside your project, and compile after realize this change).
If doens't exists, add set_target_properties:
set_target_properties( # Specifies the target library.
crypto-lib
# Specifies the parameter you want to define.
PROPERTIES IMPORTED_LOCATION
# Provides the path to the library you want to import.${PROJECT_SOURCE_DIR}
${PROJECT_SOURCE_DIR}/src/main/libs/${ANDROID_ABI}/libcrypto.so )
To:
set_target_properties( # Specifies the target library.
crypto-lib
# Specifies the parameter you want to define.
PROPERTIES IMPORTED_LOCATION
# Provides the path to the library you want to import.${PROJECT_SOURCE_DIR}
${PROJECT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libcrypto.so )
Now, build the project and run the app.
Thing related:
Dont need to add crypto statically (is libcrypto, but his name is crypto).
System.loadLibrary("crypto");
Related info:
Description of Android.mk
Port to BoringSSl (no need to me to work the app)
I hope this help!

andengine compileReleaseNdk error

I want to use andengine in my android studio project but I have ndk error while building.
Error:Execution failed for task ':andEngine:compileReleaseNdk'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
D:\Android\android-ndk-r9d\ndk-build.cmd NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\Android\workspace\simpleclock\simple_clock_as\andEngine\build\intermediates\ndk\release\Android.mk APP_PLATFORM=android-19 NDK_OUT=D:\Android\workspace\simpleclock\simple_clock_as\andEngine\build\intermediates\ndk\release\obj NDK_LIBS_OUT=D:\Android\workspace\simpleclock\simple_clock_as\andEngine\build\intermediates\ndk\release\lib APP_ABI=all
Error Code:
2
Output:
D:/Android/android-ndk-r9d/toolchains/arm-linux-androideabi-4.6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: D:\Android\workspace\simpleclock\simple_clock_as\andEngine\build\intermediates\ndk\release\obj/local/armeabi-v7a/objs/andengine_shared/D_\Android\workspace\simpleclock\simple_clock_as\andEngine\src\main\jni\src\GLES20Fix.o: in function Java_org_andengine_opengl_GLES20Fix_glVertexAttribPointer:GLES20Fix.c(.text.Java_org_andengine_opengl_GLES20Fix_glVertexAttribPointer+0x40): error: undefined reference to 'glVertexAttribPointer'
D:/Android/android-ndk-r9d/toolchains/arm-linux-androideabi-4.6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld.exe: D:\Android\workspace\simpleclock\simple_clock_as\andEngine\build\intermediates\ndk\release\obj/local/armeabi-v7a/objs/andengine_shared/D_\Android\workspace\simpleclock\simple_clock_as\andEngine\src\main\jni\src\GLES20Fix.o: in function Java_org_andengine_opengl_GLES20Fix_glDrawElements:GLES20Fix.c(.text.Java_org_andengine_opengl_GLES20Fix_glDrawElements+0x30): error: undefined reference to 'glDrawElements'
collect2: ld returned 1 exit status
make.exe: *** [D:\Android\workspace\simpleclock\simple_clock_as\andEngine\build\intermediates\ndk\release\obj/local/armeabi-v7a/libandengine_shared.so] Error 1
I suppose I'm missing some OpenGL files?
The Android Gradle plugin's NDK task does not actually use any Android.mk file that you may have provided in your jni/ folder. This was a great source of confusion for me until I figured that out.
It generates a intermediate Android.mk file during the build, based on parameters that you have set in your Gradle build script and on the content of your jni/ folder.
You can see this for yourself by inspecting the source for its NdkCompile task at https://android.googlesource.com/platform/tools/base/+/55aebda607efcc29b8d9d5e1a99d446e320ff288/build-system/gradle/src/main/groovy/com/android/build/gradle/tasks/NdkCompile.groovy.
Note the writeMakeFile(...) method on line 126.
This is why the error you are getting from the ndk-build command that runs as part of your Gradle build references the build script APP_BUILD_SCRIPT=D:\Android\workspace\simpleclock\simple_clock_as\andEngine\build\intermediates\ndk\release\Android.mk, not something like APP_BUILD_SCRIPT=D:\Android\workspace\simpleclock\simple_clock_as\andEngine\src\main\jni\Android.mk as you might expect and want it to.
There is no way of getting the Android Gradle plugin's NDK task to use your own Android.mk file (believe me if there was I would have found it!).
You have two options for getting your NDK code compiling as part of Gradle:
Figure out the correct configuration to put in your build.gradle so that the generated Android.mk file contains the required LOCAL_LDLIBS := -lGLESv2 line and any of the other lines from https://github.com/nicolasgramlich/AndEngine/blob/GLES2/jni/Android.mk that are required.
Write a custom NDK compile task that uses the AndEnginge's Android.mk file directly. I've recently had to do this myself for an NDK source set that requires more parameters than the Android Gradle plugin currently supports passing via Gradle, so it if comes to this I can provide help.
I think in this case option 1 is open and so of course the preferable solution.
Something like this added to the android defaultConfig block should work:
android {
defaultConfig {
ndk {
moduleName "myNDKModule"
stl "stlport_shared"
ldLibs "lGLESv2"
cFlags "-Werror"
}
}
}
Unfortunately I am very much not a C/native code expert (I know practically nothing) so cannot guess whether AndEngine needs LOCAL_MODULE_FILENAME and LOCAL_EXPORT_C_INCLUDES to be set to build correctly. If it does, you'll need to go with approach 2 (at least until if/when the Android Gradle NDK task supports configuring them). Though I have just checked out the AndEngine git repo and successfully run ndk-build after having removed them from its Android.mk file, which is promising.
(I found which NDK properties can be parametrised via inspection of https://android.googlesource.com/platform/tools/base/+/55aebda607efcc29b8d9d5e1a99d446e320ff288/build-system/gradle/src/main/groovy/com/android/build/gradle/internal/dsl/NdkConfigDsl.java).
I had a similar issue, and this video https://www.youtube.com/watch?v=0-rYK2oh8oo helped me to fix the build issues. Basically, you need to download (and extract) NDK from here: http://developer.android.com/ndk/downloads/index.html and specify the NDK location in Module Settings. Also, you need to alter the andEngine's build.gradle file to include
sourceSets{
main{
jni.srcDirs = []
}
}
Android.mk actually includes the line?
https://github.com/nicolasgramlich/AndEngine/blob/GLES2/jni/Android.mk#L10
LOCAL_LDLIBS := -lGLESv2
These errors indicate it.
error: undefined reference to 'glVertexAttribPointer'
error: undefined reference to 'glDrawElements'

Categories

Resources