使用NDK交叉构建到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++_staticc++_shared

  • compiler.cppstd:C++标准版本,根据您的需求进行调整。

  • os.api_level:您可以在这里查看每个Android版本/API级别的用法,并选择最符合您要求的版本。这通常是在新功能和更兼容的应用程序之间取得平衡。

  • arch:Android支持多种架构:x86x86_64armv7armv8

  • 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的包,建议采用以下方法

另请参阅