Skip to content

Instantly share code, notes, and snippets.

@jibsen
Created June 10, 2016 18:35
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
CMake functions to add compiler flags

Code

Here are two simple CMake functions that take a list of compiler flags, and append those that do not result in an error when used to the supplied variable.

Depending on which version of CMake you need to support, you might want to look into the COMPILE_FLAGS property and target_compile_options().

include(CheckCCompilerFlag)

function(add_c_compiler_flags var)
  foreach(flag ${ARGN})
    string(REGEX REPLACE "[^a-zA-Z0-9]+" "_" flag_var "CFLAG_${flag}")
    check_c_compiler_flag("${flag}" ${flag_var})
    if(${flag_var})
      set(${var} "${${var}} ${flag}")
    endif()
  endforeach()
  set(${var} "${${var}}" PARENT_SCOPE)
endfunction()
include(CheckCXXCompilerFlag)

function(add_cxx_compiler_flags var)
  foreach(flag ${ARGN})
    string(REGEX REPLACE "[^a-zA-Z0-9]+" "_" flag_var "CXXFLAG_${flag}")
    check_cxx_compiler_flag("${flag}" ${flag_var})
    if(${flag_var})
      set(${var} "${${var}} ${flag}")
    endif()
  endforeach()
  set(${var} "${${var}}" PARENT_SCOPE)
endfunction()

Examples

# Add a single flag
add_c_compiler_flags(CMAKE_C_FLAGS "-Wall")

# Add to the flags used for Release builds
add_c_compiler_flags(CMAKE_C_FLAGS_RELEASE "-fomit-frame-pointer")

# Add a list of flags
add_c_compiler_flags(CMAKE_C_FLAGS "-Wall;-Wextra;-pedantic")

# Add a long list of flags
add_c_compiler_flags(CMAKE_C_FLAGS
  -Wall
  -Wextra
  -pedantic
  -Wshadow
  -Wpointer-arith
  -Wcast-qual
  -Wcast-align
  -Wstrict-prototypes
  -Wmissing-prototypes
)

This post is CC-BY-SA, any code snippets are MIT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment