13.2 交叉编译hello world示例
NOTE:此示例代码可以在 https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-13/recipe-01 中找到,其中包含一个C++示例。该示例在CMake 3.5版(或更高版本)中是有效的,并且已经在GNU/Linux、macOS和Windows上进行过测试。
这个示例中,我们将重用“Hello World”示例,并将代码从Linux或macOS交叉编译到Windows。换句话说,我们将在Linux或macOS上配置和编译代码,并生成Windows平台的可执行文件
准备工作
我们从hello world示例(hello-world.cpp)开始:
#include <iostream>
#include <omp.h>
#include <string>
int main(int argc, char *argv[])
{
std::cout << "number of available processors: " << omp_get_num_procs()
<< std::endl;
std::cout << "number of threads: " << omp_get_max_threads() << std::endl;
auto n = std::stol(argv[1]);
std::cout << "we will form sum of numbers from 1 to " << n << std::endl;
// start timer
auto t0 = omp_get_wtime();
auto s = 0LL;
#pragma omp parallel for reduction(+ : s)
for (auto i = 1; i <= n; i++)
{
s += i;
}
// stop timer
auto t1 = omp_get_wtime();
std::cout << "sum: " << s << std::endl;
std::cout << "elapsed wall clock time: " << t1 - t0 << " seconds" << std::endl;
return 0;
}我们还将使用与前一个示例相同的CMakeLists.txt:
为了交叉编译源代码,我们需要安装一个C++交叉编译器,也可以为C和Fortran安装一个交叉编译器。可以使用打包的MinGW编译器,作为打包的交叉编译器的替代方案。还可以使用MXE (M cross environment)从源代码构建一套交叉编译器:http://mxe.cc
具体实施
我们将按照以下步骤,在这个交叉编译的“hello world”示例中创建三个文件:
创建一个文件夹,其中包括
hello-world.cpp和CMakeLists.txt。再创建一个
toolchain.cmake文件,其内容为:将
CMAKE_CXX_COMPILER设置为对应的编译器(路径)。然后,通过将
CMAKE_TOOLCHAIN_FILE指向工具链文件,从而配置代码(本例中,使用了从源代码构建的MXE编译器):现在,构建可执行文件:
注意,我们已经在Linux上获得
hello-world.exe。将二进制文件复制到Windows上。在WIndows上可以看到如下的输出:
如你所见,这个二进制可以在Windows下工作。
工作原理
由于与目标环境(Windows)不同的主机环境(在本例中是GNU/Linux或macOS)上配置和构建代码,所以我们需要向CMake提供关于目标环境的信息,这些信息记录在toolchain.cmake文件中( https://cmake.org/cmake/help/latest/manual/cmake-toolchains.7.html#cross-compiling )。
首先,提供目标操作系统的名称:
然后,指定编译器:
这个例子中,我们不需要检测任何库或头文件。如果必要的话,我们将使用以下命令指定根路径:
例如,提供MXE编译器的安装路径。
最后,调整find命令的默认行为。我们指示CMake在目标环境中查找头文件和库文件:
在主机环境中的搜索程序:
更多信息
有关各种选项的更详细讨论,请参见: https://cmake.org/cmake/help/latest/manual/cmake-toolchains.7.html#cross-compiling
Last updated
Was this helpful?