且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 CMake 在 GCC 和 Clang/LLVM 之间切换

更新时间:2023-11-10 17:05:04

CMake 在检测到要使用的 C 和 C++ 编译器时遵循环境变量 CCCXX:

CMake honors the environment variables CC and CXX upon detecting the C and C++ compiler to use:

$ export CC=/usr/bin/clang
$ export CXX=/usr/bin/clang++
$ cmake ..
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang

编译器特定标志可以通过将它们放入make override文件并指向CMAKE_USER_MAKE_RULES_OVERRIDE 变量.使用以下内容创建一个文件 ~/ClangOverrides.txt:

The compiler specific flags can be overridden by putting them into a make override file and pointing the CMAKE_USER_MAKE_RULES_OVERRIDE variable to it. Create a file ~/ClangOverrides.txt with the following contents:

SET (CMAKE_C_FLAGS_INIT                "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

SET (CMAKE_CXX_FLAGS_INIT                "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

后缀_INIT将使CMake用给定的值初始化相应的*_FLAGS变量.然后以如下方式调用cmake:

The suffix _INIT will make CMake initialize the corresponding *_FLAGS variable with the given value. Then invoke cmake in the following way:

$ cmake -DCMAKE_USER_MAKE_RULES_OVERRIDE=~/ClangOverrides.txt ..

最后强制使用LLVM binutils,设置内部变量_CMAKE_TOOLCHAIN_PREFIX.CMakeFindBinUtils 模块支持此变量:

Finally to force the use of the LLVM binutils, set the internal variable _CMAKE_TOOLCHAIN_PREFIX. This variable is honored by the CMakeFindBinUtils module:

$ cmake -D_CMAKE_TOOLCHAIN_PREFIX=llvm- ..

将所有这些放在一起,您可以编写一个 shell 包装器,它设置环境变量 CCCXX,然后使用提到的调用 cmake变量覆盖.

Putting this all together you can write a shell wrapper which sets up the environment variables CC and CXX and then invokes cmake with the mentioned variable overrides.

另请参阅此 CMake FAQ制作覆盖文件.

Also see this CMake FAQ on make override files.