首先進行NDK開發的環境是Android studio3.3.2 + gradle4.10.1 +CMake3.10.2
在新建一個Android studio ndk工程的時候,Android studio會自動給你新建好一個CMakeLists.txt和native-lib.cpp文件。並且CMakeList幫你配置好。
在nativie-lib.cpp文件中使用log是完全沒問題的
#include <jni.h>
#include <string>
#include <android/log.h>
extern "C" JNIEXPORT jstring JNICALL
Java_com_sven_jnidemo_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
__android_log_print(ANDROID_LOG_INFO,"msg","patch path:%s","hello world");
return env->NewStringUTF(hello.c_str());
}
直接Run到手機上可以在log控制檯上看到日誌
但是,如果要重新新建一個完全一樣的cpp文件(當然名稱不一樣),生成一個新的so庫。就會發現編譯不通過提示“undefined reference to '__android_log_print'
比如在CMakeList.txt進行如下配置
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 them for you.
# Gradle automatically packages shared libraries with your APK.
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).
native-lib.cpp)
add_library(
test-lib
SHARED
test.c)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries 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 this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
native-lib
test-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
}
生成一個test-lib的靜態so文件,對應test.c文件,內容和native-lib.cpp內容一樣。編譯的時候會發現test.c這一行
__android_log_print(ANDROID_LOG_INFO,"msg","patch path:%s","hello world");
無法通過,如果在cmake文件中改成
target_link_libraries( # Specifies the target library.
test-lib
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
}
會發現native-lib.cpp無法通過,所以猜測target_link_libraries只能一一對應鏈接到log
所以改成
target_link_libraries( # Specifies the target library.
test-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
target_link_libraries(
native-lib
${log-lib}
)
編譯通過,兩個so庫都能成功打印出log。
因爲Android studio在後面的版本中都用cmake來構建,所以網上搜索的那些修改gradle文件的方法都不管用。搜了一圈都沒有正確答案。