Search code examples
c++cmakecompiler-flags

Does set_target_properties in CMake override CMAKE_CXX_FLAGS?


At the beginning of my CMake project, I'm setting general compilation flags in the variable CMAKE_CXX_FLAGS, like

set(CMAKE_CXX_FLAGS "-W -Wall ${CMAKE_CXX_FLAGS}")

Later on, I need to append additional configuration-specific compilation flags (stored in BUILD_FLAGS). Can I use the following command for this:

set_target_properties(${TARGET} PROPERTIES COMPILE_FLAGS ${BUILD_FLAGS})

or do I have to add the CMAKE_CXX_FLAGS manually:

set_target_properties(${TARGET} PROPERTIES COMPILE_FLAGS "${CMAKE_CXX_FLAGS} ${BUILD_FLAGS}")

to prevent CMAKE_CXX_FLAGS being overriden by BUILD_FLAGS?


Solution

  • Use the first one:

    set_target_properties(${TARGET} PROPERTIES COMPILE_FLAGS ${BUILD_FLAGS})
    

    The flags stored in BUILD_FLAGS are appended after CMAKE_CXX_FLAGS when compiling the sources of TARGET. The documentation hints at this, but I've just tried it to make sure.

    COMPILE_FLAGS

       Additional flags to use when compiling this target's sources. 
       
       The COMPILE_FLAGS property sets additional compiler flags used to
       build sources within the target.  Use COMPILE_DEFINITIONS to
       pass additional preprocessor definitions.
    

    The full command line will be the equivalent of:

    ${CMAKE_CXX_COMPILER} ${CMAKE_CXX_FLAGS} ${COMPILE_FLAGS} -o foo.o -c foo.cc
    

    And as Ramon said, you can always check with make VERBOSE=1.