CMake should not set `CC` and `CXX` environment variables
Current Behavior
CMake sets CC
and/or CXX
environment variables on first configuration, but does not set them on subsequent reconfigurations. Those variables are exported to child processes, altering their behavior.
Depending on user environment, child processes may always break; or first succeed during initial configuration and then fail on the second one. The behavior is very volatile: things may seem to work for a while, until a subtle change in the environment cause everything to start breaking even if there were no code changes.
Observed on CMake versions 3.12.2, 3.18.2 and 3.18.4 (latest)
Related to an old closed issue #16356 (closed)
Expected Behavior
CMake should not alter environment behind the back. If any execute_command
/execute_process
needs them set, that must be done explicitly so that readers of CMakeLists.txt
know about it, and most importantly it must be done consistently such that they are always set or always unset.
Exporting CC
without CFLAGS
/CPPFLAGS
/LDFLAGS
is generally incorrect and has unpredictable results: failure if the compiler can not work without an essensial --sysroot
flag, or success if it can.
Setting CC
to a different value than CMAKE_C_COMPILER
is a common use case in cross-compilation, when CMake project targets e.g. Android but needs to compile and run a build tool (e.g. Protobuf compiler, protoc
) that targets the current host (e.g. Mac). Because most third party projects do some sort of auto-configuration, the absense of CC
is often just as important as its presense.
And since every external build system is different, there is no generic "correct" way to export CC
and CFLAGS
without having more information about the child process. Therefore, it is best not to do it implicitly.
Reproduction
Source
% cat ../CMakeLists.txt
message ( STATUS "CC=$ENV{CC}" )
project ( nothing LANGUAGES C )
# Workaround
# unset ( ENV{CC} )
# unset ( ENV{CXX} )
message ( STATUS "CC=$ENV{CC}" )
First run
% cmake ..
-- CC=
-- The C compiler identification is AppleClang 11.0.0.11000033
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
Next runs
% cmake ..
-- CC=
-- CC=