将 C++ 与 Android ndk/jni 一起使用 [英] Use C++ with Android ndk/jni
问题描述
所有 ndk 示例仅使用在标头中声明为 extern 并在 cpp 文件中定义的基本 C 函数.然后在包含jni回调的C文件中包含头文件后,一切正常.
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.
是否可以在 android ndk 中使用 C++ 类?我的应用程序不会是原生活动,它仍然会有一个重要的 java 部分,但它会调用原生 C 代码进行 CPU 密集型计算(已经用 C++ 编写,带有类和其他 C++ 内容).
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).
这是我现在的 hello-world 结构:
Here is my hello-world like strcuture for now:
文件first.h"
#ifndef FIRST_H
#define FIRST_H
class Test
{};
#endif /* FIRST_H */
文件second.cpp"
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
最后是 Android.mk
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)
相当基本,但无法编译.在 .c 文件中打开 second.cpp 在包含头文件时会引发错误,我猜这是因为它不是 C++ 文件.
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'
将其设为 .cpp 会引发以下错误:
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?
谢谢
推荐答案
可以使用 C++ 和 NDK,但 C++ 代码的文件必须具有 .cpp 扩展名.
You can use C++ with NDK, but files with C++ code must have .cpp extension.
来自 ANDROID-MK.html:
请注意,C++ 源文件的默认扩展名是.cpp".它是但是可以通过定义变量来指定不同的LOCAL_CPP_EXTENSION.不要忘记最初的点(即 '.cxx' 将工作,但不是'cxx').
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').
这篇关于将 C++ 与 Android ndk/jni 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!