cmake_minimum_required(VERSION 3.14)

set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)

add_subdirectory(../Board_Info_NiosV_bsp Board_Info_NiosV_bsp)

include(../Board_Info_NiosV_bsp/toolchain.cmake)

project(Board_Info_NiosV)

enable_language(ASM)
enable_language(C)
enable_language(CXX)

add_executable(Board_Info_NiosV.elf)

target_sources(Board_Info_NiosV.elf
    PRIVATE
        main.c
)

target_include_directories(Board_Info_NiosV.elf
    PRIVATE
    PUBLIC
)

target_link_libraries(Board_Info_NiosV.elf
    PRIVATE
        -T "${BspLinkerScript}" -nostdlib
        "${ExtraArchiveLibraries}"
        -Wl,--start-group "${BspLibraryName}" -lc -lstdc++ -lgcc -lm -Wl,--end-group
)

# Create objdump from ELF.
set(objdump Board_Info_NiosV.elf.objdump)
add_custom_command(
    OUTPUT "${objdump}"
    DEPENDS Board_Info_NiosV.elf
    COMMAND "${ToolchainObjdump}" "${ToolchainObjdumpFlags}" Board_Info_NiosV.elf >
            "${objdump}"
    COMMENT "Creating ${objdump}."
    VERBATIM
)
add_custom_target(create-objdump ALL DEPENDS "${objdump}")

# Report space free for stack + heap. Note that the file below is never created
# so the report is always output on build.
set(stack_report_file Board_Info_NiosV.elf.stack_report)
add_custom_command(
    OUTPUT "${stack_report_file}"
    DEPENDS Board_Info_NiosV.elf
    COMMAND niosv-stack-report -p "${ToolchainPrefix}" Board_Info_NiosV.elf
    COMMENT "Reporting memory available for stack + heap in Board_Info_NiosV.elf."
    VERBATIM
)
add_custom_target(niosv-stack-report ALL DEPENDS "${stack_report_file}")

# Generate HEX file(s) from Board_Info_NiosV.elf using elf2hex tool.
# Note : If ECC Full is enabled, width of 39 is set for NiosV TCM. Otherwise, 32.
add_custom_command(
    OUTPUT "intel_onchip_memory.hex"
    DEPENDS Board_Info_NiosV.elf
    COMMAND elf2hex Board_Info_NiosV.elf -o intel_onchip_memory.hex -b 0x00000000 -w 32 -e 0x0007FFFF -r 4
    COMMENT "Creating intel_onchip_memory.hex."
    VERBATIM
)
add_custom_target(create-hex ALL DEPENDS "intel_onchip_memory.hex")
