Last active
February 1, 2024 14:17
-
-
Save amir-saniyan/de99cee82fa9d8d615bb69f3f53b6004 to your computer and use it in GitHub Desktop.
Pure CMake function to convert any file into C/C++ source code, implemented with only CMake commands.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#################################################################################################### | |
# 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") | |
#################################################################################################### | |
function(embed_resource resource_file_name source_file_name variable_name) | |
if(EXISTS "${source_file_name}") | |
if("${source_file_name}" IS_NEWER_THAN "${resource_file_name}") | |
return() | |
endif() | |
endif() | |
file(READ "${resource_file_name}" hex_content HEX) | |
string(REPEAT "[0-9a-f]" 32 pattern) | |
string(REGEX REPLACE "(${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 unsigned char ${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
You can use
sizeof
operator: