在同一项目 JNI 中包含多个库依赖项

Include multiple library dependency in same project JNI

我正在尝试使用 JNI 构建一个 android 应用程序。以下是我的C++代码结构:

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

在我的 native-lib.cpp 中,我包括 dependency.h。在我的 Cmake 中,我正在为 dependencynative-lib 创建共享库 (.so),以便我可以将它们加载到代码的 Java 部分。

但是在构建代码时我无法构建 native-lib,因为它依赖于 dependency。为了快速修复,我首先构建 dependency,然后将其 link 转换为 native-lib,然后将两者加载到我的 java 端。但我知道这是错误的做事方式,因此我想知道在 JNI 中添加多个依赖项的正确方法。

以下是我的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)

这里是 Java 代码:

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: 不把 target_link_libraries 添加到 link libdependency.so 以为 Java LoadLibrary 会 link 实际上-time 不会构建,因为 native-lib 会有未定义的引用

在Android上,如果平台早于API,你只需要显式loadLibrary("dependency") 21。至于CMake

target_link_libraries(native-lib dependency)

应该可以,但如果 CMake 缓存未正确更新,您可能需要清理项目。