问题描述
我正在尝试使用JNI构建一个Android应用。以下是我的C ++代码结构:
main
-cpp
-native-lib.cpp
-dependency.h
-dependency.cpp
我的native-lib.cpp
中包括dependency.h
。在我的Cmake中,我正在为dependency
和native-lib
创建一个共享库(.so),以便可以将它们加载到代码的Java部分。
在构建代码时,我无法构建native-lib
,因为它依赖于dependency
。为了快速解决问题,我先构建dependency
,然后将其链接到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
来链接libdependency.so
并认为Java LoadLibrary
将实时链接它并没有构建,因为native-lib将具有未定义的引用
解决方法
在Android上,如果平台早于API 21,则仅需要显式loadLibrary("dependency")
。至于 CMake ,
target_link_libraries(native-lib dependency)
应该可以,但是如果CMake缓存未正确更新,则可能需要清理项目。