CMakeMacroForceAddFlags

From KitwarePublic
Revision as of 12:28, 24 April 2018 by Brad.king (talk | contribs)
Jump to navigationJump to search

Back

I have several projects that depend on the presence of certain arguments to various flags. If the user accidentally removes them, I want to forcefully put them back in while preserving any additional arguments the user may have added. The following macro is helpful for doing this. The operation is similar to a set union, but I don't deal with duplicates in either set.

# This will add arguments not found in ${parameter} to the end.  It
# does not attempt to remove duplicate arguments already existing in
# ${parameter}.

MACRO(FORCE_ADD_FLAGS parameter)
  # Create a separated list of the arguments to loop over
  SET(p_list ${${parameter}})
  SEPARATE_ARGUMENTS(p_list)
  # Make a copy of the current arguments in ${parameter}
  SET(new_parameter ${${parameter}})
  # Now loop over each required argument and see if it is in our
  # current list of arguments.
  FOREACH(required_arg ${ARGN})
    # This helps when we get arguments to the function that are
    # grouped as a string:
    #
    # ["-O3 -g"]  instead of [-O3 -g]
    SET(TMP ${required_arg}) #elsewise the Seperate command doesn't work)
    SEPARATE_ARGUMENTS(TMP)
    FOREACH(option ${TMP})
      # Look for the required argument in our list of existing arguments
      SET(found FALSE)
      FOREACH(p_arg ${p_list})
        IF (${p_arg} STREQUAL ${option})
          SET(found TRUE)
        ENDIF (${p_arg} STREQUAL ${option})
      ENDFOREACH(p_arg)
      IF(NOT found)
        # The required argument wasn't found, so we need to add it in.
        SET(new_parameter "${new_parameter} ${option}")
      ENDIF(NOT found)
    ENDFOREACH(option ${TMP})
  ENDFOREACH(required_arg ${ARGN})
  SET(${parameter} ${new_parameter} CACHE STRING "" FORCE)
ENDMACRO(FORCE_ADD_FLAGS)

Here is an example script using the macro.

SET(flags "")

MESSAGE("flags = ${flags}")
MESSAGE("forcing: -g3 -msse")
FORCE_ADD_FLAGS(flags -g3 -msse)
MESSAGE("flags = ${flags}")

MESSAGE("forcing: \"-msse -msse2\" -O3")
FORCE_ADD_FLAGS(flags "-msse -msse2" -O3)
MESSAGE("flags = ${flags}")

MESSAGE("forcing: -g3")
FORCE_ADD_FLAGS(flags -g3)
MESSAGE("flags = ${flags}")

Here's the output.

flags =
forcing: -g3 -msse
flags =  -g3 -msse
forcing: "-msse -msse2" -O3
flags =  -g3 -msse -msse2 -O3
forcing: -g3
flags =  -g3 -msse -msse2 -O3

Note that forcing a particular argument only adds it if it isn't already present and any previous arguments are left intact.



CMake: [Welcome | Site Map]