#!/bin/bash # Usage: create a file foo.c, make foo a symlink to this script # When foo is executed, this script silently compiles foo.c into .make-and-exec-binaries/foo (if necessary) and execs that with the arguments provided. # Making a symlink named foo-dbg causes it to compile foo.c with -DDEBUG. # To customise the compilation, you can set a CFLAGS env var before running foo. sourcename="${0%-dbg}.c" if [[ "$0" == *-dbg ]]; then opt='-Og -fsanitize=undefined,address -DDEBUG'; else opt='-O3'; fi targetfile="$(dirname "$0")/.make-and-exec-binaries/$(basename "$0")" if [[ ! -f "${targetfile}" || "${sourcename}" -nt "${targetfile}" || "${BASH_SOURCE}" -nt "${targetfile}" ]]; then mkdir -p "$(dirname "$0")/.make-and-exec-binaries" gcc -Wall -Wextra -Wshadow -Werror ${opt} ${CFLAGS} -o "${targetfile}" "${sourcename}" || exit testfile="$(dirname "$0")/.$(basename "${0%-dbg}")-test" if [[ -f "${testfile}" ]]; then "${testfile}" || { st=$?; touch -d '1970-01-01T00:00:00Z' "${targetfile}"; exit "${st}"; } fi fi exec "${targetfile}" "$@"