以添加和构建两个C++库libA和libB为例。libA依赖于libB,因此需要在构建libA之前构建和安装libB。
add_library(libB SHARED
source_file_b1.cpp
source_file_b2.cpp
)
target_include_directories(libB PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include
)
// 库B依赖于某些外部库,在此处添加链接
target_link_libraries(libB
${log-lib}
)
cmake .
make libB
sudo make install
// 库A依赖库B
add_library(libA SHARED
source_file_a1.cpp
source_file_a2.cpp
)
target_include_directories(libA PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include
)
// 库A依赖于库B,因此需要添加库B的链接
target_link_libraries(libA
libB
${log-lib}
)
cmake .
make libA
sudo make install
#include
#include "libA.h"
#include "libB.h"
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
// 使用libA和libB
libB_func();
libA_func();
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
add_library(native-lib SHARED
native-lib.cpp)
target_include_directories(native-lib PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/../include
)
// 链接libA和libB
target_link_libraries(native-lib
libA
libB
${log-lib}
)
android {
// ...
defaultConfig {
// ...
externalNativeBuild {
cmake {
cppFlags ""
// 引用C++库
target_link_libraries {
native-lib
}
}
}
}
}
完成以上步骤后,可以使用libA和libB中的函数。注意控制C++库之间的依赖关系以确保在使用库时不会出现运行时错误。