开发者

undefined reference when including a local header file in android NDK

开发者 https://www.devze.com 2023-02-25 14:55 出处:网络
I construct a simple android application which uses ndk with JNI. The application has onw .cpp(debugTest.cpp) file that is used to link java and c++ with jni and another .c(javaEssentials.c) file with

I construct a simple android application which uses ndk with JNI. The application has onw .cpp(debugTest.cpp) file that is used to link java and c++ with jni and another .c(javaEssentials.c) file with it's header(javaEssentials.h). When I include in the .cpp file the .c file(#include "javaEssentials.c") no error is reported when compiling. When I include in the .cpp file the header the compiler reports error of undefined reference of the functions the .c file has.It is real strange problem and I can't understand why is this happening. As usual I have an include declaration of the header file in the .c file.

My android.mk is:

# build file written to describe the C and C++ source files to the Android NDK

L开发者_运维问答OCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := debugTest
LOCAL_SRC_FILES := debugTest.cpp

include $(BUILD_SHARED_LIBRARY)

Any ideas why this is happening ?


You should only include headers (or alternatively use prototypes) to allow your C files to compile.

After compilation you would still have an error complaining about "undefined reference to `methodName'".

This is because C++ compilers encode the namespace of methods inside a cpp file. It doesn't do this for methods (or importantly, for method calls) inside of c files. This means that compiled c files cannot naturally access methods in compiled c++ code, even if the source code would suggest just that.

You can however tell the compiler that the method is going to be called by the "C" language therefore it will not encode the method namespace. You can instruct the compiler to do this by modifying the method in your cpp to look like this:

extern "C" int methodName()
{
    return 1;
}

methodName() will now be accessible from your compiled C file.


You should to #include the .h files, not .c or .cpp.


Add to your Android.mk file:

LOCAL_C_INCLUDES := $(LOCAL_PATH)include_dir1 \
                    $(LOCAL_PATH)include_dir2 \
                    ...

For every directory where there are .h files

0

精彩评论

暂无评论...
验证码 换一张
取 消