Reputation: 92
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 is my C library I want to import into Android Studio
#include "mylib.h"
int total_foo;
int foo(float y, float z) {
total_foo = y + z;
return total_foo;
}
2) mylib.h is the header file for 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) Command for .o file (using NDK with make_standalone_toolchain.py)
$CC -o mylib.o -c mylib.c
4) Command for .a file
ar rcs mylib.a mylib.o
5) Create a Native C++ Project
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.
*Putting the code into Android Studio and using Cmake is out since I will only have a Static Library file. *
TLDR: How to add a pre-compiled *.a file into Android Studio.
Upvotes: 4
Views: 4332
Reputation: 58517
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)
Upvotes: 8