Skip to content

Instantly share code, notes, and snippets.

@Rexagon
Created October 13, 2020 20:18
Show Gist options
  • Save Rexagon/0b40d688a375b779de9d23b268f6e88c to your computer and use it in GitHub Desktop.
Save Rexagon/0b40d688a375b779de9d23b268f6e88c to your computer and use it in GitHub Desktop.
Function that converts any file into C/C++ source code.
####################################################################################################
# This function converts any file into C/C++ source code.
# Example:
# - input file: data.dat
# - output file: data.h
# - variable name declared in output file: DATA
# - data length: sizeof(DATA)
# embed_resource("data.dat" "data.h" "DATA" UNSIGNED)
####################################################################################################
function(embed_resource resource_file_name source_file_name variable_name type)
if ("${type}" STREQUAL "SIGNED")
set(array_element_type "char")
else()
set(array_element_type "unsigned char")
endif()
file(READ ${resource_file_name} hex_content HEX)
string(REPEAT "[0-9a-f]" 32 column_pattern)
string(REGEX REPLACE "(${column_pattern})" "\\1\n" content "${hex_content}")
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1, " content "${content}")
string(REGEX REPLACE ", $" "" content "${content}")
set(array_definition "static const ${array_element_type} ${variable_name}[] =\n{\n${content}\n};")
set(source "// Auto generated file.\n${array_definition}\n")
file(WRITE "${source_file_name}" "${source}")
endfunction()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment