cmakecflags

CMake SET command not working as expected (CMake not setting value of predefined cached variable)


I'm using CMake in my builds. I'm trying to set compiler flags like this:

set(CMAKE_C_FLAGS_DEBUG "-option1 -option2 -option3")

however, my build fails because one of the compiler flags is not set.

When I check the value of the variable in CMake-GUI is empty:

enter image description here

Can someone point out what is happening?


Solution

  • What you see with cmake-gui is the cache status. You only see there variables that you explicitly cache, or predefined cmake cached variables.

    Now, when you do:

    set(CMAKE_C_FLAGS_DEBUG "-option1 -option2 -option3")
    

    You are doing something particular: you are setting a "local" (not cached) variable which has the same name of a predefined cmake cached variable. In C++ it would be like defining a local variable with the same name of a global variable: the local variable will hide your global variable.

    From the set documentation. (The documentation calls "normal" what I called "local")

    Both types can exist at the same time with the same name but different values. When ${FOO} is evaluated, CMake first looks for a normal variable 'FOO' in scope and uses it if set. If and only if no normal variable exists then it falls back to the cache variable 'FOO'.

    You are already effectively setting CMAKE_C_FLAGS_DEBUG, and the compiler will use the flags you have specified. You can check it with:

    message(STATUS "CMAKE_C_FLAGS_DEBUG = ${CMAKE_C_FLAGS_DEBUG}")
    

    So, your building is failing for another reason. Check which command line make generates: make VERBOSE=1.

    By the way, I suggest you append your flags to the predefined ones, by doing:

    set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -option1 -option2 -option3")
    

    Also consider using the other predefined variable CMAKE_C_FLAGS, in case you want those settings to be propagated to all build types.


    Edit:
    After some iterations it turned out the problem was that the build type (CMAKE_BUILD_TYPE) was not set from cmake. This can either be done through the cmake-gui interface, or adding something like -DCMAKE_BUILD_TYPE=Debug or -DCMAKE_BUILD_TYPE=Release to the cmake command line.