include(CheckCCompilerFlag)
include(CheckCXXCompilerFlag)

function(add_cflag flag)
  string(REGEX REPLACE "[^a-zA-Z0-9_]" "_" var ${flag})
  if(NOT DEFINED HAVE_C${var})
    message(STATUS "checking for C compiler flag: ${flag}")
  endif()
  set(CMAKE_REQUIRED_QUIET TRUE)

  check_c_compiler_flag("${flag}" HAVE_C${var} QUIET)
  if(HAVE_C${var})
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}" PARENT_SCOPE)
  endif()
endfunction()

function(add_cxxflag flag)
  string(REGEX REPLACE "[^a-zA-Z0-9_]" "_" var ${flag})
  if(NOT DEFINED HAVE_CXX${var})
    message(STATUS "checking for C++ compiler flag: ${flag}")
  endif()
  set(CMAKE_REQUIRED_QUIET TRUE)

  check_cxx_compiler_flag("${flag}" HAVE_CXX${var} QUIET)
  if(HAVE_CXX${var})
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE)
  endif()
endfunction()

function(add_dllflag flag)
  string(REGEX REPLACE "[^a-zA-Z0-9_]" "_" var ${flag})
  if(NOT DEFINED HAVE_LD${var})
    message(STATUS "checking for C++ compiler flag: ${flag}")
  endif()
  set(CMAKE_REQUIRED_QUIET TRUE)

  check_c_compiler_flag("${flag}" HAVE_LD${var} QUIET)
  if(HAVE_LD${var})
    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${flag}" PARENT_SCOPE)
  endif()
endfunction()

macro(add_flag flag)
  add_cflag(${flag})
  add_cxxflag(${flag})
endmacro()
