首页 > 解决方案 > Clang 链接 .so 库 libc++_shared.so

问题描述

我在 Android NDK 应用程序中的本机 C++ 代码中出现错误

我的 main.cpp

#include <stdio.h>

int main() 
{
  printf("Hello, world\n");
  return 0;
}

main.c 完全一样。如果我跑

/home/rip/Music/android-ndk-r19b/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android26-clang -pie main.c

然后

adb push a.out /data/local/tmp

adb shell /data/local/tmp/a.out

一切正常。但如果我跑

/home/rip/Music/android-ndk-r19b/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android26-clang++ -pie main.cpp

然后

adb push a.out /data/local/tmp

 adb shell /data/local/tmp/a.out

错误信息是:

CANNOT LINK EXECUTABLE "/data/local/tmp/a.out": library "libc++_shared.so" not found

然后我试着跑

/home/rip/Music/android-ndk-r19b/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android26-clang++ -pie hello1.cpp  /home/rip/Music/android-ndk-r19b/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/aarch64-linux-android/libc++_shared.so

链接库,但它无论如何都不起作用。

标签: androidc++android-ndkclang

解决方案


错误信息是:

CANNOT LINK EXECUTABLE "/data/local/tmp/a.out": library "libc++_shared.so" not found

这是预期的行为。与标准 C 库(使用 simple 构建程序时链接到的标准 C 库*-clang)不同,C++ 不是系统库。您必须像任何其他第三方库一样在设备上提供它。

引用自官方文档

Note: libc++ is not a system library. If you use libc++_shared.so, it must be included in your APK. If you're building your application with Gradle this is handled automatically.

And:

If you're using clang directly in your own build system, clang++ will use c++_shared by default. To use the static variant, add -static-libstdc++ to your linker flags.

So either link with C++ statically by passing -static-libstdc++ to compiler. Or copy the libc++_shared.so (from <NDK>/sources/cxx-stl/llvm-libc++/libs/arm64-v8a/ in your case) and run like:

adb push a.out libc++_shared.so /data/local/tmp/
adb shell
cd /data/local/tmp/
LD_LIBRARY_PATH=. ./a.out

Other than the LLVM's Standard C++ library discussed above, there's also a limited system C++ runtime (/system/lib(64)/libstdc++.so) which "provides support for the basic C++ Runtime ABI". But "The system STL will be removed in a future NDK release."


推荐阅读