7 Dec 2013

#! shebang for C programs

For testing it is sometimes very tedious to always compile and run the small C programs I use as utilities. So I thought, why not use the shebang for this. After investigating how the shebang mechanism works I figured a small bash script would do the trick.

The following script needs to be somewhere in your $PATH, I call the script "C":

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env bash

filename=$(basename "$1")
filename="${filename%.*}"

# need to compile?
if [ "$1" -nt "/tmp/runcache/$filename" ]; then
 mkdir -p /tmp/runcache/
 # get rid of shebang line in C program and compile it
 tail -n +2 "$1" > /tmp/runcache/$filename.c
 gcc -Wall -std=c99 $CC_OPTS -o \
  /tmp/runcache/$filename \
  /tmp/runcache/$filename.c
fi

# first parameter is the old executable, 
# remove it and poitn to the new one
shift 

/tmp/runcache/$filename "$@"

Once in place, you can add the shebang line "!#/usr/bin/env C" to your C code in the first line, make it executable and run it like a script. Here is our test C program:


1
2
3
4
5
6
7
8
#!/usr/bin/env C 

#include <stdio.h>

int main() {
 printf("Hello World\n");
 return 0;
}

Then run it like this:

$ chmod 700 test.c
$ ./test.c
Hello World
$