简体   繁体   中英

Android NDK C++ Class undefined Reference

First.h

#ifndef FIRST_H
#define FIRST_H

class Test
{
public:
void create();
void test();

private:


};



#endif /* FIRST_H */

Second.cpp

#include "first.h"


#ifdef __cplusplus
extern "C" {
#endif

jint

Java_com_example_ndkcpp2_MainActivity_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{
    Test t;
    t.test();

}

#ifdef __cplusplus
}
#endif

When I do a NDK-Build on second.cpp I got

pp2/jni/second.cpp:44: error: undefined reference to 'Test::test()' collect2: ld returned 1 exit status

Using C++, you declare Class in .h file and write implementation in .cpp file. for example, you created First.h, then you should create First.cpp, in which write your method implementation like void Test::test(){} . Remember to add First.cpp to your makefile(Android.mk) for compilation.

You have multiple options here assuming that you have a first.cpp file that you implemented the Test class correctly. Without being able to see your Android.mk, I will go through all options:

Build First.cpp as a static or shared library and add this library to your module which compiles Second.cpp. Your Android.mk should look like:

LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE    := firstlib
LOCAL_C_INCLUDES := path/to/first.h
LOCAL_SRC_FILES := first.cpp
include $(BUILD_STATIC_LIBRARY)

If you would like First to be a shared library instead of a static library, change include $(BUILD_STATIC_LIBRARY) line to:

include $(BUILD_SHARED_LIBRARY)

Now, your second lib is compiled as follows:

include $(CLEAR_VARS)

LOCAL_MODULE    := second
LOCAL_C_INCLUDES := path/to/first.h
LOCAL_C_INCLUDES += path/to/second.h
LOCAL_SRC_FILES := second.cpp
LOCAL_STATIC_LIBRARIES := firstlib

include $(BUILD_SHARED_LIBRARY)

If firstlib is built as shared library, you can link it by chaning LOCAL_STATIC_LIBRARIES += firstlib line to the following:

LOCAL_SHARED_LIBRARIES += firstlib

As a second solution, you can build first.cpp as a part of the second lib and this way you don't have to worry about linking against the first library. This is more like a design choice and how you would like to shape up your libraries:

include $(CLEAR_VARS
LOCAL_MODULE    := libtwolib-second
include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-second
LOCAL_C_INCLUDES := path/to/first.h
LOCAL_C_INCLUDES += path/to/second.h
LOCAL_SRC_FILES := first.cpp
LOCAL_SRC_FILES += second.cpp

include $(BUILD_SHARED_LIBRARY)

Finally, you can find a sample of the first approach in your NDK directory, under samples/twolibs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM