Skip to content

Instantly share code, notes, and snippets.

@Eggbertx
Last active May 26, 2019 21:50
Show Gist options
  • Select an option

  • Save Eggbertx/d546d4c92ecf630976f97af7db88d25e to your computer and use it in GitHub Desktop.

Select an option

Save Eggbertx/d546d4c92ecf630976f97af7db88d25e to your computer and use it in GitHub Desktop.
A shell script that uses ld/xxd to pack files into an object file or header file to be used by C programs
#!/bin/sh
set -euo pipefail
function usage {
echo "usage: $0 [-o outfile] [-m text|binary] [-i] file..."
echo "options:"
echo " -h show usage info"
echo " -i use xxd (usually comes with vim) to generate a C-style"
echo " include header rather than an object file (overrides -m)"
echo " -m <mode> binary mode (see -b section of ld man page for more info)"
echo " -o <file> output object file"
exit 0
}
infiles=""
outfile=""
mode="binary"
include=0
if [ $# == 0 ]; then usage; fi
while test $# -gt 0; do
case "$1" in
-o)
shift
if [ -z $1 ] || [ "$outfile" != "" ]; then usage; fi
outfile=$1
echo "outfile=$outfile"
shift
;;
-m|--mode)
shift
mode=$1
shift
# if [ $mode != "text" ] && [ $mode != "binary" ]; then
# usage
# fi
;;
-i|--include)
shift
include=1
# shift
;;
-h|--help)
usage
;;
*)
if [ "$1" != "" ]; then
echo "Adding file '$1'"
infiles="$infiles $1"
fi
shift
;;
esac
done
if [ -z "$outfile" ]; then
if [ $include = 1 ]; then
outfile="_embed.h"
else
outfile="_embed.obj"
fi
fi
if [ $include = 1 ]; then
for i in $infiles; do
xxd -i $i >> $outfile
done
echo "To embed the given file(s), add the following to your source code:"
echo "#include \"$outfile\""
else
ld -r -b $mode $infiles -o $outfile
externs=$(objdump -x $outfile | grep -oE '[^ ]+$' | grep _binary_)
if [ -z "$externs" ]; then
echo "Failed getting object file info"
exit 1
fi
echo "To embed the given file(s), add the following lines to your source code:"
for e in $externs; do
echo "extern const char $e;"
done
echo "Then run gcc -o yourprogram $outfile src1.c src2.c..."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment