option(ENABLE_SANITIZER "Enable ASan+LSan+UBSan sanitizer (Debug build only)" OFF)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --std=gnu99")
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wcast-align")
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wuninitialized")
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wformat=2")
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-function")
if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 5)
	set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror=incompatible-pointer-types")
endif ()
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-unused-parameter")
if (CMAKE_C_COMPILER_ID MATCHES "Clang")
	set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-newline-eof")
	set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-gnu-zero-variadic-macro-arguments")
endif()

if(CMAKE_BUILD_TYPE)
	string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_TOLOWER)
	if(CMAKE_BUILD_TYPE_TOLOWER STREQUAL "debug")
		if(ENABLE_SANITIZER)
			# enable AddressSanitizer + LeakSanitizer + UndefinedBehaviorSanitizer
                        #set (ASAN_OPTIONS "fast_unwind_on_malloc=0:strict_string_checks=1:detect_stack_use_after_return=1")
                        #add_definitions(-DASAN_OPTIONS="${ASAN_OPTIONS}")
			set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -ggdb")
			set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fsanitize=address")
			set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fsanitize=bounds")
			set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fsanitize=alignment")
			set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fsanitize=undefined")
			set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -fsanitize=null")
			set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wmissing-braces")
			set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wmissing-field-initializers")
			set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wno-unused-function")

		endif()
	endif()
endif()
