Skip to content

Instantly share code, notes, and snippets.

@islandcontroller
Last active March 12, 2025 22:23
Show Gist options
  • Save islandcontroller/04ed64498605bd3ae821c1d5d5e19a1a to your computer and use it in GitHub Desktop.
Save islandcontroller/04ed64498605bd3ae821c1d5d5e19a1a to your computer and use it in GitHub Desktop.
CMake Helper Scripts
# ------------------------------------------------------------------------------
# @brief
# Import raw binary data
#
# The binary data will be imported into an object file and placed into the
# ".rodata" section of the target. Each data import adds three global symbols:
# - <data_name>_start: Start marker (extern unsigned char)
# - <data_name>_end: End marker (extern unsigned char)
# - <data_name>_size: Size of the data (extern unsigned int)
#
# Replace "elf32-littleriscv" with target architecture:
# - elf32-littleriscv: 32-bit RISC-V
# - elf32-littlearm: 32-bit ARM
#
# @param[in] target_name Target name
# @param[in] data_name Prefix for the data symbols
# @param[in] binary_file Binary file to be imported
#-------------------------------------------------------------------------------
function(add_binary_data target_name data_name binary_file)
cmake_path(GET binary_file PARENT_PATH parent)
cmake_path(GET binary_file FILENAME filename)
string(REGEX REPLACE "[^a-zA-Z1-9]" "_" binary_sym ${filename})
set(out_filename ${data_name}${CMAKE_C_OUTPUT_EXTENSION})
set(out_path ${CMAKE_CURRENT_BINARY_DIR}/${data_name}${CMAKE_C_OUTPUT_EXTENSION})
add_custom_command(OUTPUT ${out_filename}
COMMAND ${CMAKE_OBJCOPY} -I binary ${filename}
--redefine-sym _binary_${binary_sym}_start=${data_name}_start
--redefine-sym _binary_${binary_sym}_end=${data_name}_end
--redefine-sym _binary_${binary_sym}_size=${data_name}_size
--rename-section .data=.rodata
-O elf32-littleriscv ${out_path}
WORKING_DIRECTORY ${parent}
)
add_custom_target(${data_name} DEPENDS ${out_path})
add_dependencies(${target_name} ${data_name})
target_link_libraries(${target_name} PRIVATE ${out_path})
endfunction()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment