How does native C++ code get linked to an external library, within an android studio project?

  android-studio, c++, cmake, opencv

I have an android app, that calls some native C++ code, where the C++ code uses opencv.

I have OpenCV-for-Android installed and working correctly on the android side.

I can build that C++ code on its own (in a C++ wrapper), and it can use its (separate) opencv library fine.

When I build that native code through an android studio project though, that same opencv doesn’t get linked to that C++ code. That is, I get linker errors on every call to an opencv method/class/etc.

I don’t see an appreciable difference in the CMakeLists files.

Is there a difference, in how native code gets built+linked within android studio, vs how it gets built and linked on its own?

Said differently, do you have to do anything different in android studio, in order for libraries called and used entirely within the native code, to link? I would have assumed that android studio isn’t involved in anything that happens when native code gets built.

The CMakeLists.txt file, in Android Studio:


project(project_name LANGUAGES CXX)

cmake_minimum_required(VERSION 3.4.1)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_BUILD_TYPE Release)

set(OpenCV_DIR /usr/local/lib/cmake/opencv4)
set(OpenCV_HOME /usr/local/lib/cmake/opencv4)

find_package(OpenCV 4.5 REQUIRED PATHS "/usr/local/lib/cmake/opencv4")


include_directories( ${OpenCV_INCLUDE_DIRS} )

set(SOURCE_PATH ../../source)
include(${SOURCE_PATH}/sources.cmake)

add_library(${PROJECT_NAME} SHARED
        ProjectJNIInterface.cpp
        ${PROJECT_SOURCES}
        )

target_include_directories(${PROJECT_NAME} PUBLIC ${SOURCE_PATH}/src ${OpenCV_INCLUDE_DIRS})

target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})

The only relevant difference between the two CMakeLists files (standalone vs android studio) is the add_library command, and the fact that I had to set OpenCV_DIR in the android studio one, in order for opencv to be found. The standalone add_library command is

add_library(${PROJECT_NAME} SHARED
        ${PROJECT_SOURCES}
        ${PROJECT_HEADERS}
        )

I’ve gone through a lot of questions on how to call opencv code natively from android, how to add opencv as a library to android studio, and how to add opencv to a C++ project, none of which (I believe) are the problem.

Source: Windows Questions C++

LEAVE A COMMENT