使用 NDK 将 Conan 交叉构建到 Android¶
在本例中,我们将演示如何将 Conan 包交叉构建到 Android。
首先,从 下载页面 下载 Android NDK 并解压。在 MacOS 上,您也可以使用 brew install android-ndk 进行安装。
然后,进入 conan 配置主目录下的 profiles 文件夹(运行 conan config home 检查),并创建一个名为 android 的文件,内容如下:
include(default)
[settings]
# Just an example, you need to use your real settings
os=Android
os.api_level=21
arch=armv8
compiler=clang
compiler.version=12
compiler.libcxx=c++_shared
compiler.cppstd=14
[conf]
# Use your path here
tools.android:ndk_path=/usr/local/share/android-ndk
您可能需要修改:
compiler.version:请查阅 NDK 文档,或查找包含编译器可执行文件的bin文件夹,例如x86_64-linux-android31-clang。在 Macos 安装中,它位于 NDK 路径 +toolchains/llvm/prebuilt/darwin-x86_64/bin。运行./x86_64-linux-android31-clang --version来检查正在运行的clang版本并调整配置文件。compiler.libcxx:支持的值是c++_static和c++_shared。compiler.cppstd:C++ 标准版本,请根据您的需求进行调整。os.api_level:您可以在 此处 查看每个 Android 版本/API 级别的用法,并选择最符合您要求的版本。这通常是在新功能和更兼容的应用之间取得平衡。arch:Android 支持多种架构:x86、x86_64、armv7和armv8。tools.android:ndk_path配置:填写解压后的 NDK 的位置。
如果您在 Windows 上,则需要一个类似 make 的构建系统,如 MinGW-Make 或 Ninja。我们可以在配置文件中使用 [tool_requires] 直接为 Ninja 进行配置。
...
[conf]
# Use your path here
tools.android:ndk_path=C:\ws\android\android-ndk-r23b
tools.cmake.cmaketoolchain:generator=Ninja
[tool_requires]
ninja/[*]
使用 conan new 命令创建一个“Hello World” C++ 库示例项目
$ conan new cmake_lib -d name=hello -d version=1.0
然后,我们可以指定 android 配置文件,我们的 hello 库将被构建到 Android。
$ conan create . --profile android
[ 50%] Building CXX object CMakeFiles/hello.dir/src/hello.cpp.o
[100%] Linking CXX static library libhello.a
[100%] Built target hello
...
[ 50%] Building CXX object CMakeFiles/example.dir/src/example.cpp.o
[100%] Linking CXX executable example
[100%] Built target example
库和 test_package 可执行文件都将为 Android 构建,因此我们无法在本地计算机上使用它们。
除非您拥有 root 权限的 Android 设备,否则直接运行测试应用程序或使用构建的库是不可能的。因此,更常见的是构建一个使用 hello 库的 Android 应用程序。
也可以使用 Conan 的 tool-requires 中的 android-ndk。ConanCenter 中已经有一个包含 AndroidNDK 的 Conan 包,因此编写一个类似以下的配置文件:
[settings]
os=Android
os.api_level=21
arch=armv8
compiler=clang
compiler.version=18
compiler.libcxx=c++_shared
compiler.cppstd=14
build_type=Release
# You might need Ninja conf and tool-requires in Windows too
[tool_requires]
android-ndk/[*]
这样将自动从 ConanCenter 下载最新的 android-ndk,并自动注入和应用它来构建包。请注意,要在生产环境中使用来自 ConanCenter 的包,推荐采用以下方法。
另请参阅
请查看 将 Conan 集成到 Android Studio 示例,了解如何在原生 Android 应用程序中使用您的 C++ 库。
请查看教程 如何使用 Conan 交叉编译您的应用程序。