undefined reference to `__android_log_print‘

报错描述

在 Android NDK 相关的工程构建中,出现报错:

undefined reference to `__android_log_print'

翻译成 QM 能理解的话: 在链接阶段, 遇到一个需要被链接的符号 __android_log_print, 但是没有在给出的依赖库里面找到 __android_log_print 符号。

复制代码
[2/2] Linking CXX executable testbed
FAILED: testbed
cmd.exe /C "cd . && D:\soft\android-ndk\r26-beta1\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++.exe --target=aarch64-none-linux-android24 --sysroot=D:/soft/android-ndk/r26-beta1/toolchains/llvm/prebuilt/windows-x86_64/sysroot -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security   -fno-limit-debug-info -static-libstdc++ -Wl,--build-id=sha1 -Wl,--no-rosegment -Wl,--no-undefined-version -Wl,--fatal-warnings -Wl,--no-undefined -Qunused-arguments CMakeFiles/testbed.dir/main.cpp.o -o testbed  -latomic -lm && cd ."
ld.lld: error: undefined symbol: __android_log_print
>>> referenced by main.cpp:10 (D:/github/min-repros/test_android_log/r21e/main.cpp:10)
>>>               CMakeFiles/testbed.dir/main.cpp.o:(main)
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.

为什么要链接 __android_log_print

QM 的初始诉求是, 不准开发的代码依赖 log 库。那么谁用了 __android_log_print 符号, 目的又是什么?

__android_log_print 符号, 对应到 C/C++ 函数, 用于打印日志并显示到 Android LogCat。啥意思? 我们开发者提供的 .a/.so 库,最终是放到 Android App 里使用的,而 Android App 是一个 GUI 界面程序, 它是没有控制台的 log 输出给用户看的。 也就是说,如果用户的一些交互操作, 导致 Android App 崩溃了, 并且打算从 Android Studio 的 LogCat 去检查报错问题(此时很可能是 Android Java/Kotlin开发者),那么 LogCat 的报错信息是非常有用出的: 快速定位问题。

当然, 你也可以让 Android NDK 开发者完全不使用 __android_log_print. 那意味着: 如果 Android App 出现 Crash,Android App 的 Java/Kotlin 开发者无从查起, Android NDK 开发者也拿不到 log 内容, 无法定位 bug。

复现代码

cpp 复制代码
#include <string.h>
#include <jni.h>
#include <android/log.h>

#define  LOG_TAG    "foo"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)

int main()
{
    LOGI("test");
}

链接 log 库

cmake 复制代码
add_executable(testbed main.cpp)
target_link_libraries(testbed PRIVATE log) # 增加这一行
相关推荐
鱼儿也有烦恼1 天前
01.搭建Android Studio开发环境
android·android studio
m0_738120721 天前
PHP代码审计基础——面向对象(四)
android·开发语言·网络·安全·github·php
Coffeeee1 天前
搞Android的怎么可能搞不懂Context Engineering?
android·人工智能·ai编程
Carson带你学Android1 天前
Gemini Nano 开发实战:让你的App轻松拥有端侧 AI 功能
android·ai编程
TDengine (老段)1 天前
TDengine SMA 索引 — 块级/文件级统计索引
android·大数据·服务器·数据库·人工智能·时序数据库·tdengine
心中有国也有家1 天前
AtomGit Flutter 鸿蒙客户端: AnimatedScale 与 AnimatedContainer 联合实战
android·javascript·flutter·华为·harmonyos
恋猫de小郭1 天前
Flutter Windows 开始支持 Impeller ,还修复了多窗口 bug
android·前端·flutter
鱼儿也有烦恼1 天前
07.RecyclerView、SwipeRefreshLayout、SmartRefreshLayout
android
三少爷的鞋1 天前
Kotlin Flow 深入解析:`stateIn()` 的真正核心,其实是 SharingStarted
android
心中有国也有家2 天前
AtomGit Flutter 鸿蒙客户端:ModalBottomSheet 实战
android·javascript·学习·flutter·华为·harmonyos