Last Updated: February 25, 2016
·
587
· colindean

Run C as a script, recompiling only when changed

Hot on the heels of a great tip on running C code as a script, I modified it a bit to recompile only when the file changes. It uses the TMPDIR envvar instead of mktmp.

//bin/cat /dev/null; mkdir -p $TMPDIR; HASH="`md5sum $0`"; FILE="$TMPDIR/$0_$HASH"; gcc -o "$FILE" "$0" && "$FILE" "$@"; exit

#include <stdio.h>

int main(int argc, char *argv[]) {
  int i;
  printf("Arguments:\n");
  for (i = 0; i < argc; i++) {
    printf("%d: %s\n", i, argv[i]);
  }
}