Best way of adding compiler flags in toolchain

The CMAKE_<LANG>_FLAGS_INIT variables will only have an effect the first time CMake is run in a build directory. After that, the CMAKE_<LANG>_FLAGS variables will already be set and CMAKE_<LANG>_FLAGS_INIT gets ignored. I also mention the following in my Professional CMake book, which may also be relevant to you here:

Unfortunately, there are some inconsistencies in how CMake combines developer-specified ..._INIT options with the defaults it normally provides. In most cases, CMake will append further options to those specified by ...INIT variables, but with some platform/compiler combinations (particularly older or less frequently used ones), developer-specified ..._INIT values can be discarded. This stems from the history of these variables, which used to be for internal use only and always unilaterally set the ..._INIT values. From CMake 3.7, the ..._INIT variables were documented for general use and the behavior was switched to appending rather than replacing for the commonly used compilers. The behavior for very old or no longer actively maintained compilers was left unmodified.

All that said, the CMAKE_<LANG>_FLAGS_INIT variables probably still are the most appropriate way to do what you’re trying to achieve. I’d only look for a different method if you’re using a toolchain where CMake doesn’t handle those variables in the way that you need them to.

1 Like