Thursday, 15 June 2017

android - How to call c++ methods from JNI



in Java code:



System.loadLibrary("twolib-second");

int z = add(1, 2);


public native int add(int x, int y);


first.cpp:



#include "first.h"

int first(int x, int y) {
return x + y; }



first.h:



#ifndef FIRST_H
#define FIRST_H

extern int first(int x, int y);

#endif /* FIRST_H */



second.c:



#include "first.h"
#include

jint
Java_com_example_jniexample_MainActivity_add( JNIEnv* env,
jobject this,
jint x,

jint y )
{
return first(x, y);
}


Android.mk:



LOCAL_PATH:= $(call my-dir)


# first lib, which will be built statically
#
include $(CLEAR_VARS)

LOCAL_MODULE := libtwolib-first
LOCAL_SRC_FILES := first.cpp

include $(BUILD_STATIC_LIBRARY)

# second lib, which will depend on and include the first one

#
include $(CLEAR_VARS)

LOCAL_MODULE := libtwolib-second
LOCAL_SRC_FILES := second.c

LOCAL_STATIC_LIBRARIES := libtwolib-first

include $(BUILD_SHARED_LIBRARY)



I keep getting this error:




/home/username/ndk/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld:./obj/local/armeabi/objs/twolib-second/second.o: in function Java_com_example_jniexample_MainActivity_add:jni/second.c:26:



error: undefined reference to 'first' collect2: ld returned 1 exit status make: * [obj/local/armeabi/libtwolib-second.so] Error 1



Answer



you need to use extern "C" to surround the declaration in first.h in order to call func first from second.c.




I guess this is because your first file is compiled as cpp but second as c. the difference is the name mangling. you can call linux bin util command nm to the static lib and object file to list up symbols and see wjere the rob is. i think you will see in the static lib there is a mangled symbol of funcion first; a unmangled symbol of func in the second.o



you will see many many undefined references while programming with ndk. linux bin utils will be nice tool to make life easier.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...