Use C++ with Android ndk/jni

pot2mayo picture pot2mayo · Jun 21, 2011 · Viewed 31k times · Source

All the ndk samples only make use of basic C functions declared as extern in the header and defined in the cpp file. Then after including the header file in the C file containing the jni callback, everything works fine.

Is it possible to use C++ classes with the android ndk? My application is not going to be a native activity, it will still have an important java part but it will call native C code for CPU-intensive computation (already written in C++, with classes and other C++ stuff).

Here is my hello-world like strcuture for now:

File "first.h"

#ifndef FIRST_H
#define FIRST_H

class Test
{};

#endif /* FIRST_H */

File "second.cpp"

#include <jni.h>
#include "first.h"

#ifdef __cplusplus
extern "C" {
#endif

jint Java_com_example_twolibs_TwoLibs_add( JNIEnv*  env,
                                      jobject  this,
                                      jint     x,
                                      jint     y )
{
    Test t;
    return 0;
}

#ifdef __cplusplus
}
#endif

And finally Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

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

include $(BUILD_SHARED_LIBRARY)

Pretty basic but that does not compile. Turning second.cpp in a .c file raises an error when including the header file, I guess this is because it is not a C++ file.

error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Test'

Making it .cpp raises the following error:

make: *** No rule to make target `/cygdrive/c/android-ndk-r5c/samples/twolibs/jni/second.c', needed by `/cygdrive/c/android-ndk-r5c/samples/two-libs/obj/local/armeabi/objs/twolib-second/second.o'.  Stop.

Any idea how I can make that thing compile?

Thanks

Answer

Michael picture Michael · Jun 21, 2011

You can use C++ with NDK, but files with C++ code must have .cpp extension.

From ANDROID-MK.html:

Note that the default extension for C++ source files is '.cpp'. It is however possible to specify a different one by defining the variable LOCAL_CPP_EXTENSION. Don't forget the initial dot (i.e. '.cxx' will work, but not 'cxx').