首先进行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文件的方法都不管用。搜了一圈都没有正确答案。