user2591946
user2591946

Reputation: 163

How to build an shared library and call it in other ndk program

I want to build an shared library. To build it, I need to call another shared library. Here is what I did:

1.Create one Android project,named "BuildLib",and add a new folder "jni" under the project directory. Contents of jni folder:

jni-->Android.mk
-->Application.mk
-->add.cpp
-->add.h add.cpp just do two numbers addition:

add.h:

int add(int a,int b);

add.cpp:

#include "add.h"  
int add(int a,int b){
    return a+b;}

Android.mk:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES  := add.cpp 
LOCAL_MODULE     := add
include $(BUILD_SHARED_LIBRARY)

After build the project,I got libadd.so under directory $(BUILDLIB)/libs/armeabi/.

Create another Android project, named "CallLib". Copy libadd.so and add.h to jni folder, create Android.mk, Application.mk, and call_add.cpp.

Android.mk:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := libadd.so
LOCAL_MODULE := add_prebuilt
include $(PREBUILD_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_C_INCLUDES := $(LOCAL_PATH)
LOCAL_SRC_FILES  := call_add.cpp 
LOCAL_MODULE     :=  native
LOCAL_SHARED_LIBRARIES := add_prebuilt
include $(BUILD_SHARED_LIBRARY)

call_add.cpp:

#include "add.h"
int call_add(){return add(1,2);}

After all above, I build the CallLib project, but got the error:

undefined reference to 'add(int, int)';

I think the libadd.so can not be found, but I don't know how to modify. Does anyone know how I can fix this? Any help will be appreciated.

Upvotes: 16

Views: 21118

Answers (2)

18446744073709551615
18446744073709551615

Reputation: 16852

Just in case anyone needs it:

A bit hackish way to keep the linker happy:

LOCAL_LDLIBS := -llog

or

LOCAL_LDLIBS := -L$(LOCAL_PATH)/lib -lMyStuff

Less hackish:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := xyz
LOCAL_SRC_FILES += xyz/xyz.c
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)    # this builds libxyz.so


include $(CLEAR_VARS)
LOCAL_MODULE    := abc
LOCAL_SHARED_LIBRARIES := xyz    # <=== !!! this makes libabc.so dependent on libxyz.so
LOCAL_SRC_FILES := abc/abc.c
#LOCAL_LDLIBS := ...
include $(BUILD_SHARED_LIBRARY)    # this builds libabc.so

Upvotes: 1

mbrenon
mbrenon

Reputation: 4941

In your second Android.mk, try replacing the first module with:

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES := libadd.so
LOCAL_MODULE := add_prebuilt
LOCAL_EXPORT_C_INCLUDES := add.h
include $(PREBUILD_SHARED_LIBRARY)

The LOCAL_EXPORT_C_INCLUDES flag should attach the header information to the add_prebuilt module, so it can be linked with your final library.

Upvotes: 4

Related Questions