首页 > 解决方案 > 带有静态库的 Android Studio 中的本机 C++ 代码

问题描述

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

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 以包含有关库文件的信息?

标签: c++android-studiogradlecmakestatic-libraries

解决方案


这是我的解决方案:首先,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'
    }
}

推荐阅读