Android:在 Android Studio 中链接外部静态 C/C++ 库 [英] Android: Linking a external static C/C++ Library in Android Studio

查看:160
本文介绍了Android:在 Android Studio 中链接外部静态 C/C++ 库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多使用 Cmake 使本机代码在 Android Studio 中工作的答案,但是关于如何将预编译的 C/C++ 库包含到 Android 中的答案并不多.以下是我为尝试使本机库(首先尝试使用 .a)工作而采取的步骤.

I've seen many answers to get Native Code working in Android Studio with using Cmake however, not many answers on how to include a pre-compiled C/C++ library into Android. Here are the steps I've taken to try and get a Native Library(trying first with .a) to work.

1) mylib.c 是我想导入到 Android Studio 中的 C 库

#include "mylib.h"


    int total_foo;

    int foo(float y, float z) { 
    total_foo = y + z;
    return total_foo;

    }

2) mylib.h 是 mylib.c 的头文件

#ifndef _MYLIB_H_
#define _MYLIB_H_

    #define MAX_FOO  20

        struct foo_struct {  
        int x;
        float y;
    };
    typedef struct foo_struct foo_struct;

    extern int total_foo;   

    extern int foo(float y, float z); 

#endif

3) .o 文件的命令(使用带有 make_standalone_toolchain.py 的 NDK)

$CC -o mylib.o -c mylib.c 

4) .a 文件的命令

ar rcs mylib.a mylib.o

5) 创建本机 C++ 项目

现在这就是我被困的地方.我已经创建了具有本机 C++ 支持的 Android Studio 项目,并且需要弄清楚将预编译的 mylib.a 文件放在哪里才能使函数调用foo".我看到了所有不同类型的地方,如 jniLibs 文件夹、libs 和 cpp 文件夹.但没有例子说明之后做什么.就像将 Native Library 添加到 Gradle 中一样.

Now this is where I am stuck. I've created the Android Studio project with Native C++ support and need to figure out where to put my pre-compiled mylib.a file to be able to make the function call "foo". I seen all different types of places like the jniLibs folder , libs , and cpp folder. But no examples of what to do after. Like adding the Native Library into the Gradle.

*将代码放入 Android Studio 并使用 Cmake 已经过时了,因为我只有一个静态库文件.*

*Putting the code into Android Studio and using Cmake is out since I will only have a Static Library file. *

TLDR:如何将预编译的 *.a 文件添加到 Android Studio.

TLDR: How to add a pre-compiled *.a file into Android Studio.

推荐答案

假设你有一个 mylib.a 是用 NDK 构建的,你可以在你的主共享库中链接它像这样:

Assuming that you have a mylib.a somewhere that was built with the NDK, you can link against it in your main shared library like this:

CMakeLists.txt:

cmake_minimum_required(VERSION 3.4.1)

add_library(native-main-lib SHARED src/main/cpp/native-lib.cpp)

add_library(my_lib STATIC IMPORTED)
set_target_properties(my_lib PROPERTIES IMPORTED_LOCATION path/to/mylib.a)
set_target_properties(my_lib PROPERTIES INCLUDE_DIRECTORIES path/to/mylib/include)

target_link_libraries(native-main-lib my_lib)

这篇关于Android:在 Android Studio 中链接外部静态 C/C++ 库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆