我想將C++文件導入到我的android項目中。首先,我使用android studio創建了一個支持C++的項目。它提供了骨架項目結構。我用add_library方法通過CMakeLists.text文件加載我的文件。我可以成功加載我的C++文件並能夠在項目視圖中看到。當我試圖調用從mClient.cpp的方法我的家鄉 - lib.cpp裏,我得到了Android NDK項目中未定義的引用錯誤
未定義的引用爲「Hello()」
錯誤。由於我沒有看到任何IDE警告,我可以說我的文件已成功加載。但它在編譯時不起作用。我也嘗試通過cmake加載add_executable,但它也會產生相同的錯誤。請讓我知道我的配置和設置中缺少什麼?我是NDK和CMake的新手。 謝謝你的時間。
mClinet.cpp
#include "mClient.h"
static int hello(){
return 1;
}
mClient.h
#ifdef __cplusplus
extern "C" {
#endif
static int hello();
#ifdef __cplusplus
}
#endif
#endif
這是我CMake.text文件。
# Sets the minimum version of CMake required to build the native
# library. You should either keep the default value or only pass a
# value of 3.4.0 or lower.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds it for you.
# Gradle automatically packages shared libraries with your APK.
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -UNDEBUG")
add_library(# Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
# Associated headers in the same location as their source
# file are automatically included.
src/main/cpp/native-lib.cpp
src/main/cpp/mClient.cpp)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because system libraries are included in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library(# Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log)
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in the
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries(native-lib android log)
我想從我的家鄉 - lib.cpp致電問候()
#include <jni.h>
#include <string>
#include "mClient.h"
extern "C"
jstring
Java_com_zawmyohtet_hellondk_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
int myInt = hello();
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
@Eichhörnchen如果外部「C」由於名稱改變而不存在,則JNI調用將不起作用,這是完全合法的。 –