include(CheckFunctionExists)

macro(check_c_fortran_function_exists _func_base _result)
  string(TOLOWER "${_func_base}" _func_base_lower)
  string(TOUPPER "${_func_base}" _func_base_upper)
  set(${_result} FALSE)
  foreach(_func ${_func_base_lower}_;${_func_base_lower};${_func_base_lower}__;${_func_base_upper};${_func_base_upper}_)
    check_function_exists(${_func} _${_func}_found)
    if(_${_func}_found)
      set(${_result} ${_func})
      break()
    else()  # try appending c++ libs if depend on c++ runtime
      foreach(_cxxlib -lstdc++;-lc++)
        cmake_push_check_state()
        set(CMAKE_REQUIRED_LIBRARIES "${CMAKE_REQUIRED_LIBRARIES};${_cxxlib}")
        check_function_exists(${_func} _${_func}_found_with_${_cxxlib})
        cmake_pop_check_state()
        if(_${_func}_found_with_${_cxxlib})
          set(${_result} ${_func})
          break()
        endif()
      endforeach()
      if(${_result})
        break()
      endif()
    endif()
  endforeach()
endmacro()