简体   繁体   中英

Include multiple library dependency in same project JNI

I'm trying to build an android app using JNI. The following is my C++ code structure:

main
  -cpp
    -native-lib.cpp
    -dependency.h
    -dependency.cpp

In my native-lib.cpp I'm including dependency.h . In my Cmake, I'm creating a shared library (.so) for dependency and native-lib so that I can load them in my Java part of the code.

While building the code however I cannot build native-lib because it has a dependency on dependency . For a quick fix, I'm building the dependency first and then linking it to native-lib and then loading the two in my java side. But I know it is the wrong way of doing things, hence I wanted to know the right way of adding multiple dependencies in JNI.

The following is my Cmake:

cmake_minimum_required(VERSION 3.4.1)
include_directories(Include)
add_library( # Sets the name of the library.
        dependency

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        dependency.cpp )

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).
        native-lib.cpp )

# Once the so is being built I'm adding it myself and linking it. 
# I don't want to do this but link it automatically
target_link_libraries( # Specifies the target library.
        native-lib

        # Links the target library to the log library
        # included in the NDK.
        ${CMAKE_CURRENT_SOURCE_DIR}/../jniLibs/armeabi-v7a/libdependency.so)

Here is the Java code:

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("dependency");
        System.loadLibrary("native-lib");
    }
    
    // Some other functions
}

PS: Not adding target_link_libraries to link libdependency.so thinking that Java LoadLibrary will link it in real-time does not build as native-lib would have undefined references

On Android, you only need to explicitly loadLibrary("dependency") if the platform is older than API 21. As for CMake ,

target_link_libraries(native-lib dependency)

should work, but you may need to clean the project if the CMake caches don't get properly updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM