# Minimum CMake version
cmake_minimum_required(VERSION 3.10)

# Relative path to toolchain file
set(CMAKE_TOOLCHAIN_FILE "toolchain.cmake")

# Project name
project("dmacache-rm57l" C ASM)

# Export json file containing compiler calls
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Path to HALCoGen files
set(HALCOGEN_DIR "${PROJECT_SOURCE_DIR}/HALCoGen")

# List source files to be compiled
file(GLOB SOURCES
    "${PROJECT_SOURCE_DIR}/source/*.[cs]"
    "${HALCOGEN_DIR}/source/*.[cs]"
    )

# Add executable target
add_executable(${PROJECT_NAME} ${SOURCES})

# Change target suffix to have <name>.out
set_target_properties(${PROJECT_NAME} PROPERTIES SUFFIX ".out")

# Clear all compiler flags, as the host might have the CFLAGS environment
# variable set to some default flags for the host, but we are cross-compiling,
# thus we do not want to use them
set(CMAKE_C_FLAGS "")

# Include directories
target_include_directories(${PROJECT_NAME} PRIVATE
    # Toolchain include directories
    ${TOOLCHAIN_INCLUDE_DIR}
    # Projet include directories
    include
    ${HALCOGEN_DIR}/include
    )

# Definitions name
target_compile_definitions(${PROJECT_NAME} PRIVATE
    _RM57Lx_
    )

# Architecture-related compiler flags
target_compile_options(${PROJECT_NAME} PRIVATE
    -march=armv7-r
    -mfloat-abi=softfp
    -mfpu=vfpv3-d16
    )

# General compiler flags
target_compile_options(${PROJECT_NAME} PRIVATE
    -O0
    -g
    -gdwarf-3
    -gstrict-dwarf
    -Wall
    -MD
    # Keep functions in separate sections to allow linker to dump unused ones
    -ffunction-sections
    -fdata-sections
    )

# Architecture-related linker flags
target_link_libraries(${PROJECT_NAME}
    -march=armv7-r
    -mfloat-abi=softfp
    -mfpu=vfpv3-d16
    )

# Linker script
target_link_libraries(${PROJECT_NAME}
    -T ${PROJECT_SOURCE_DIR}/ldscript.ld
    )

# Other linker flags
target_link_libraries(${PROJECT_NAME}
    ${LINKER_FLAGS}
    -Wl,-Map=${PROJECT_NAME}.map
    --specs=nosys.specs
    # Let linker exclude unused sections
    -Wl,--gc-sections
    )

# Print executable size
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
    COMMAND "${SIZE}" "${PROJECT_NAME}.out"
    )
