option(USE_ASAN "Enable Address Sanitizer, if your compiler supports it" ON)
if(USE_ASAN)
	include(CheckCXXSourceCompiles)
	# If the compiler understands -fsanitize=address, add it to the flags (gcc since 4.8 & clang since version 3.2)
	set(CMAKE_REQUIRED_FLAGS_BAK "${CMAKE_REQUIRED_FLAGS}")
	set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fsanitize=address")
	CHECK_CXX_SOURCE_COMPILES("int main() { return 0; }" FLAG_FSANA_SUPPORTED)
	set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS_BAK}")

	if(FLAG_FSANA_SUPPORTED)
		set(asan_flag "-fsanitize=address")
	else(FLAG_FSANA_SUPPORTED)
		# Alternatively, try if it understands -faddress-sanitizer (clang until version 3.2)
		set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -faddress-sanitizer")
		CHECK_CXX_SOURCE_COMPILES("int main() { return 0; }" FLAG_FASAN_SUPPORTED)
		set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS_BAK}")

		if(FLAG_FASAN_SUPPORTED)
			set(asan_flag "-faddress-sanitizer")
		endif(FLAG_FASAN_SUPPORTED)
	endif(FLAG_FSANA_SUPPORTED)

	if(FLAG_FSANA_SUPPORTED OR FLAG_FASAN_SUPPORTED)
		set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${asan_flag}" PARENT_SCOPE)
		set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${asan_flag}" PARENT_SCOPE)
		set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${asan_flag}" PARENT_SCOPE)
		set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${asan_flag}" PARENT_SCOPE)
	endif()

endif(USE_ASAN)
