Android Studio 中带有静态库的原生C++代码

Native C++ Code in Android Studio with a Static Library

本文关键字:原生 C++ 代码 静态 Studio Android      更新时间:2023-10-16

我正在尝试在Android Studio和CMake中制作本机C++代码。我的C++代码使用预编译的静态库(.a 文件(。 我在C++代码中包含其标头 .h。我还在我的CMakeList中链接了.h和.a文件的位置.txt如下所示:

include_directories(".h file location")

然后:

add_library(lib_fastcv STATIC IMPORTED)
set_target_properties(lib_fastcv PROPERTIES IMPORTED_LOCATION
".a file location")

最后:

target_link_libraries (...lib_fastcv....)

但是,一旦我使用 .a 静态库中的任何函数,它就会抱怨它无法识别该函数,这意味着静态库没有正确链接到我的C++代码。

有谁知道我还需要做什么? 我是否也应该编辑我的 build.gradle 以包含有关库文件的信息?

这是我的解决方案: 所以,首先,CMake 一开始使用起来可能很奇怪。

1- native-lib1 是 CMake 的输出产品。后来的java只会看到这个的.so

add_library( # This is out .so product (libnative-lib1.so)
native-lib1
# Sets the library as a shared library.
SHARED
# These are the input .cpp source files
native-lib.cpp
SRC2.cpp
Any other cpp/c source file you want to compile
)

2-您在souse文件中包含的任何库,其.h都需要在此处解决:

target_include_directories(# This is out .so product (libnative-lib1.so)
native-lib1 PRIVATE
${CMAKE_SOURCE_DIR}/include)

3-您使用的任何实际库,其atual.a或.cpp都应以这种方式添加到CMake:

target_link_libraries(
# This is out .so product (libnative-lib1.so)
native-lib1
#These are any extra library files that I need for building my source .cpp files to final .so product
${CMAKE_SOURCE_DIR}/lib/libfastcv.a
# Links the target library to the log library
# included in the NDK.
${log-lib})

然后 build.gradle 应该提到我们希望它采用哪些 abi 格式,以确保您预先构建的 .a 文件兼容。

flavorDimensions "version"
productFlavors {
create("arm7") {
ndk.abiFilters("armeabi-v7a")
}

最后,请注意,以下命令无法过滤 abis 和上面的命令工作,即使它们在逻辑和形式上看起来与我相似:

cmake {
cppFlags "-std=c++11"
abiFilters 'armeabi-v7a'
}
}
ndk {
// Specifies the ABI configurations of your native
// libraries Gradle should build and package with your APK.
// This is not working to eliminate
abiFilters 'armeabi-v7a'
}
}