CMAKE_CXX_FLAGS set by the toolchain file are not used when compiling the feature test programs
When testing a C++ feature, CMake does not use the CMAKE_CXX_FLAGS
set by the toolchain file.
Steps to reproduce
Given the following toolchain file:
# toolchain.cmake
get_property(in_try_compile GLOBAL PROPERTY IN_TRY_COMPILE)
if(in_try_compile)
set(CMAKE_CXX_FLAGS "--not-passed-to-compiler" CACHE STRING "" FORCE)
endif()
The following program:
// main.cpp
int main() {}
And the following CMakeLists.txt
file:
project(test)
add_executable(main main.cpp)
Then by running cmake --debug-trycompile . -DCMAKE_CXX_FLAGS=--original-flag -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake
and observing the generated CMakeLists.txt
file:
cmake_minimum_required(VERSION 3.16.3.0)
project(CMAKE_TRY_COMPILE CXX)
set(CMAKE_VERBOSE_MAKEFILE 1)
set(CMAKE_CXX_FLAGS "--original-flag")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COMPILE_DEFINITIONS}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${EXE_LINKER_FLAGS}")
include_directories(${INCLUDE_DIRECTORIES})
set(CMAKE_SUPPRESS_REGENERATION 1)
link_directories(${LINK_DIRECTORIES})
cmake_policy(SET CMP0065 OLD)
cmake_policy(SET CMP0083 OLD)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "/home/julien/cmake-toolchain-bug/CMakeFiles/CMakeTmp")
add_executable(cmTC_2825c "/home/julien/cmake-toolchain-bug/CMakeFiles/CMakeTmp/testCXXCompiler.cxx")
target_link_libraries(cmTC_2825c ${LINK_LIBRARIES})
We can see that the CMAKE_CXX_FLAGS
variable is overwritten by the command line argument.
Why does it matter
I use an LLVM-based compiled with custom options that can be activated by -mllvm -some-option
. If these options are activated but cannot be applied to the program then the compiler emits a warning. CMake considers that a warning from the compiler means that a feature cannot be safely used. Consequently I cannot pass my flags via CMAKE_CXX_FLAGS
on the command line.