Skip to content

Instantly share code, notes, and snippets.

@metasim
Created June 23, 2011 13:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metasim/1042527 to your computer and use it in GitHub Desktop.
Save metasim/1042527 to your computer and use it in GitHub Desktop.
Poor man's resource compiler
#!/bin/bash
# Poor man's resource compiler
# Converts given file into compilable byte stream via
# C code header and implementation files.
# Based on original by http://www.linuxjournal.com/users/mitch-frazier
#
if [[ $# -ne 1 ]]; then
echo "Usage: $0 FILENAME"
exit 1
fi
file=$1
if [[ ! -f "$file" ]]; then
echo "File not found: $file"
exit 1
fi
CNAME=${file}
CNAME=${CNAME//-/_}
CNAME=${CNAME//./_}
VNAME=$(basename ${CNAME})
MNAME=$(echo ${VNAME} | tr "[:lower:]" "[:upper:]")
DTS=$(date)
CMD=$(basename $0)
COMMENT=$(cat << EOF
/*
* Automatically generated with $CMD
* from $file by $USER on $DTS
*/
EOF)
cat > ${VNAME}.h << EOF
$COMMENT
#ifndef __${MNAME}_H
#define __${MNAME}_H
extern unsigned char ${VNAME}[];
extern unsigned int ${VNAME}_size;
#endif // __${MNAME}_H
EOF
cat > ${VNAME}.c << EOF
$COMMENT
#include "${VNAME}.h"
unsigned char ${VNAME}[] = {
EOF
hexdump -v -e '16/1 "0x%02x," "\n"' $file | \
sed -e '$s/0x ,//g' >> ${VNAME}.c
SIZE=$(cat $file | wc -c)
cat >> ${VNAME}.c << EOF
};
unsigned int ${VNAME}_size = $SIZE;
EOF
@metasim
Copy link
Author

metasim commented Jun 27, 2011

Corresponding CMake script to generate source:

find_program(CIFY c-ify.sh HINTS ${CMAKE_CURRENT_LIST_DIR} NO_DEFAULT_PATH)

function(add_wrapped_resources SRCS_VAR)
    set(_OUTDIR ${CMAKE_BINARY_DIR})

    # Make generated header files visible
    include_directories(${_OUTDIR})

    foreach(_F ${ARGN})
        get_filename_component(_FNAME ${_F} NAME)
        string(REPLACE "." "_" _BASENAME ${_FNAME})
        set(_OUTPUTS ${_OUTDIR}/${_BASENAME}.c ${_OUTDIR}/${_BASENAME}.h) 

        # Make sure the build system knows the file is generated.
        set_source_files_properties(${_OUTPUTS} PROPERTIES GENERATED TRUE)

        # Call script to wrap resources.
        add_custom_command(
            OUTPUT ${_OUTPUTS}
            WORKING_DIRECTORY ${_OUTDIR}
            COMMAND ${CIFY} ${_F}
            DEPENDS ${CIFY}
            MAIN_DEPENDENCY ${_F})
        list(APPEND _GENSRCS ${_OUTPUTS})

    endforeach()

    set(${SRCS_VAR} ${_GENSRCS} PARENT_SCOPE)
endfunction()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment