CMake cross-compiling: C flags from toolchain file ignored
Solution 1:
I've found a temporary solution by replacing the line
SET(CMAKE_C_FLAGS "-std=gnu99")
by
SET(CMAKE_C_FLAGS "-std=gnu99" CACHE STRING "" FORCE)
Solution 2:
I just wanted to add some background information (discussed e.g. here how to setup cmake_c/xx_flags per toolchain?).
In short, the CMAKE_<LANG>_FLAGS
variables are cached by design in the CMake<Lang>Information.cmake
scripts (meaning you could change them in CMake's GUI application after the configure step).
So you have to - if setting them in the Toolchain file - put them in the cache first. CMake's own script (executed after the Toolchain file) does not come with a FORCE
, so it won't overwrite it again.
Take a look into CMakeCInformation.cmake (from share\cmake-2.8\Modules):
set(CMAKE_C_FLAGS_INIT "$ENV{CFLAGS} ${CMAKE_C_FLAGS_INIT}")
# avoid just having a space as the initial value for the cache
if(CMAKE_C_FLAGS_INIT STREQUAL " ")
set(CMAKE_C_FLAGS_INIT)
endif()
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS_INIT}" CACHE STRING
"Flags used by the compiler during all build types.")
As you can see, the official way to do it would be using CMAKE_C_FLAGS_INIT
to inject additional flags. The problem there is, that later changes in the Toolchain file would not be recognized (the cache won't be overwritten, see above).
Taken all this into account, your temporary solution is the right choice. To be really sure - because the Toolchain file is parsed twice during the Configuration/Generation process - you could even add an UNSET
call before setting CMAKE_C_FLAGS
in your toolchain file:
UNSET(CMAKE_C_FLAGS CACHE)
SET(CMAKE_C_FLAGS "-std=gnu99" CACHE STRING "" FORCE)
Another often found solution is to use something like:
add_definitions(" -std=gnu99")
to inject compile flags (but this is not build configuration aware, as the variable definitions are). See also CMake clang and c++0x
With CMake 2.8.12 there were new commands introduced, so you could do (not tested, just to show the possibilities):
add_compile_options("$<$<CONFIG:RELASE>:-std=gnu99>")
add_compile_options("$<$<CONFIG:DEBUG>:-std=gnu99 -g3>")
See What is the modern method for setting general compile flags in CMake? and CMake generator expression, differentiate C / C++ code for more on this.