对同一语言的多个编译器使用 CMake

2021-12-26 00:00:00 configuration build cmake c++

似乎 CMake 认为所有 C++ 源文件都应该有一个,而且只有一个 CMAKE_CXX_COMPILER.我找不到在每个目标的基础上覆盖它的方法.这使得使用内置 CMake 工具在单个 CMakeLists.txt 中混合主机和交叉编译变得非常困难.

It seems like CMake is fairly entrenched in its view that there should be one, and only one, CMAKE_CXX_COMPILER for all C++ source files. I can't find a way to override this on a per-target basis. This makes a mix of host-and-cross compiling in a single CMakeLists.txt very difficult with the built-in CMake facilities.

所以,我的问题是:为同一语言(即 C++)使用多个编译器的最佳方法是什么?

So, my question is: what's the best way to use multiple compilers for the same language (i.e. C++)?

推荐答案

CMake 无法做到这一点.

It's impossible to do this with CMake.

CMake 只保留一组编译器属性,这些属性由 CMakeLists.txt 文件中的所有目标共享.如果要使用两个编译器,则需要运行 CMake 两次.这甚至适用于例如从同一个编译器工具链构建 32 位和 64 位二进制文??件.

CMake only keeps one set of compiler properties which is shared by all targets in a CMakeLists.txt file. If you want to use two compilers, you need to run CMake twice. This is even true for e.g. building 32bit and 64bit binaries from the same compiler toolchain.

解决这个问题的快速而肮脏的方法是使用自定义命令.但是你最终会得到基本上美化的 shell 脚本,这可能不是你想要的.

The quick-and-dirty way around this is using custom commands. But then you end up with what are basically glorified shell-scripts, which is probably not what you want.

干净的解决方案是:不要将它们放在同一个 CMakeLists.txt 中!无论如何,您无法在不同架构之间进行链接,因此无需将它们放在同一个文件中.您可以通过将 CMake 脚本的公共部分重构为单独的文件并include() 它们来减少冗余.

The clean solution is: Don't put them in the same CMakeLists.txt! You can't link between different architectures anyway, so there is no need for them to be in the same file. You may reduce redundancies by refactoring common parts of the CMake scripts into separate files and include() them.

这里的主要缺点是您无法使用单个命令进行构建,但是您可以通过使用您最喜欢的脚本语言编写一个包装器来解决这个问题,它负责调用不同的 CMake-makefile.

The main disadvantage here is that you lose the ability to build with a single command, but you can solve that by writing a wrapper in your favorite scripting language that takes care of calling the different CMake-makefiles.

相关文章