Background
CMake has the option to pass in an environment variable CFLAGS to prepend to the CMAKE_C_FLAGS environment variable used in compiling. I am using this option running CMake in a windows platform.
Ex (enabling the -Wall
compiler flag):
cmake -E env CFLAGS="-Wall" cmake <path-to-source>
The above command is supposed to create a temporary environment and set CFLAGS to -Wall
and then run cmake
again within this temporary environment. It is a proposed solution in this SO question. HOWEVER, it does not work as expected. The CMAKE_C_FLAGS
are not initialized with the CFLAGS
passed through. When printing the CMAKE_C_FLAGS
at the beginning of the CMakeLists.txt the set value for -Wall
does not appear.
This is a distinct functionality from simply setting the CMAKE_C_FLAGS environment value using the -D
option specified in the CMake CLI Documentation.
cmake -DCMAKE_C_FLAGS="-Wall" <path-to-source>
Doing so will override the system variables set by CMake which leads to compilation failure. For instance in our project the CMAKE_C_FLAGS
can be seen to be by default set to:
CMAKE FLAGS: /DWIN32 /D_WINDOWS /W3
However if the cmake -D
code is run, it will overwrite the initial CMAKE_C_FLAGS
:
CMAKE FLAGS: -Wall
In the cmake documentation it explains:
CFLAGS - CMake 3.11.4 Documentation
Default compilation flags to be used when compiling C files. Will only be used by CMake on the first configuration to determine CC default compilation flags, after which the value for CFLAGS is stored in the cache as CMAKE_C_FLAGS. For any configuration run (including the first), the environment variable will be ignored if the CMAKE_C_FLAGS variable is defined.
Now there is a workaround for this if one has the ability to adjust the CMakeLists.txt file itself, which is to create a -D
option parameter that accepts an arbitrary string and appends it to the CMAKE_C_FLAGS
.
if (NOT "${compileOption_C}" STREQUAL "OFF")
set(CMAKE_C_FLAGS "${compileOption_C} ${CMAKE_C_FLAGS}")
endif()
However this is a bit of a bodge and does not answer why the initial CFLAGS
option does not work.
Question
How does one add compiler flags using the CMake CLI without overwriting cached or default CMAKE_C_FLAGS
values, knowing that CFLAGS
is not working as intended?