首先确保CmakeLists中已添加Log库
通过Android Studio 新建NDK项目后,需要确保CmakeLists.txt
已添加Log库
# 从系统库中查找依赖库
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)
# 配置库的依赖关系
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
${log-lib})
然后在cpp文件中引入Log库
#include <android/log.h>
//定义输出的TAG
const char * LOG_TAG = "LOG_TGA";
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGT(...) __android_log_print(ANDROID_LOG_INFO,"alert",__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
然后使用即可
extern "C" JNIEXPORT jstring JNICALL
Java_com_heiko_ndklogtest_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
LOGI("打印了日志........");
LOGD("hello:%s", hello.c_str());
return env->NewStringUTF(hello.c_str());
}
输出结果如下
I/LOG_TGA: 打印了日志........
D/LOG_TGA: hello:Hello from C++
参考
https://blog.csdn.net/weixin_33779515/article/details/88037942