| 1 |
include(CheckCCompilerFlag) |
| 2 |
include(CheckCXXCompilerFlag) |
| 3 |
|
| 4 |
# check_add_add_flag(<variable> <flag> [DEBUG_ONLY | RELEASE_ONLY]) |
| 5 |
# |
| 6 |
# Add a C or C++ compilation flag to the current scope |
| 7 |
# |
| 8 |
# Can optionally add the flag to Debug or Release configurations only, use this when |
| 9 |
# targeting multi-configuration generators like Visual Studio or Xcode. |
| 10 |
# Release configurations means NOT Debug, so it will work for RelWithDebInfo or MinSizeRel too. |
| 11 |
# |
| 12 |
# If the flag is added successfully, the variables FLAG_C_<variable> and FLAG_CXX_<variable> |
| 13 |
# may be set to ON. |
| 14 |
# |
| 15 |
# Examples: |
| 16 |
# check_and_add_flag(FOO -foo) |
| 17 |
# check_and_add_flag(ONLYDEBUG -onlydebug DEBUG_ONLY) |
| 18 |
# check_and_add_flag(OPTMAX -O9001 RELEASE_ONLY) |
| 19 |
|
| 20 |
function(check_and_add_flag var flag) |
| 21 |
set(genexp_config_test "1") |
| 22 |
if(ARGV2 STREQUAL "DEBUG_ONLY") |
| 23 |
set(genexp_config_test "$<CONFIG:Debug>") |
| 24 |
elseif(ARGV2 STREQUAL "NO_DEBINFO_ONLY") |
| 25 |
set(genexp_config_test "$<NOT:$<OR:$<CONFIG:Debug>,$<CONFIG:RelWithDebInfo>>>") |
| 26 |
elseif(ARGV2 STREQUAL "RELEASE_ONLY") |
| 27 |
set(genexp_config_test "$<NOT:$<CONFIG:Debug>>") |
| 28 |
elseif(ARGV2) |
| 29 |
message(FATAL_ERROR "check_and_add_flag called with incorrect arguments: ${ARGN}") |
| 30 |
endif() |
| 31 |
|
| 32 |
set(is_c "$<COMPILE_LANGUAGE:C>") |
| 33 |
set(is_cxx "$<COMPILE_LANGUAGE:CXX>") |
| 34 |
set(test_flags_c) |
| 35 |
set(test_flags_cxx) |
| 36 |
|
| 37 |
# The Visual Studio generators don't support COMPILE_LANGUAGE |
| 38 |
# So we fail all the C flags and only actually test CXX ones |
| 39 |
if(CMAKE_GENERATOR MATCHES "Visual Studio") |
| 40 |
set(is_c "0") |
| 41 |
set(is_cxx "1") |
| 42 |
else() |
| 43 |
# Otherwise assume the compile follows GCC syntax |
| 44 |
# and fail when the option is known but invalid. |
| 45 |
set(test_flags_c "${test_flags_c}-Werror ") |
| 46 |
set(test_flags_cxx "${test_flags_cxx}-Werror ") |
| 47 |
endif() |
| 48 |
|
| 49 |
check_c_compiler_flag("${test_flags_c}${flag}" FLAG_C_${var}) |
| 50 |
if(FLAG_C_${var}) |
| 51 |
add_compile_options("$<$<AND:${is_c},${genexp_config_test}>:${flag}>") |
| 52 |
endif() |
| 53 |
|
| 54 |
check_cxx_compiler_flag("${test_flags_cxx}${flag}" FLAG_CXX_${var}) |
| 55 |
if(FLAG_CXX_${var}) |
| 56 |
add_compile_options("$<$<AND:${is_cxx},${genexp_config_test}>:${flag}>") |
| 57 |
endif() |
| 58 |
endfunction() |