Created
January 19, 2013 10:12
-
-
Save shouya/4571771 to your computer and use it in GitHub Desktop.
use C program code as a script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# -*- shell-script -*- | |
# cas - c as script | |
# A script which support act C language code as a script. | |
# | |
# Usage: | |
# cas [COMPILE_OPTIONS] [source_file] [EXECUTE_ARGUMENTS] | |
# the source_file should be appoint otherwise it'll use /dev/stdin automically. | |
# | |
# There's a typical way to appoint a c code as a script, just add a | |
# `shebang' line at the first line of code, the `cas' will deal this line. | |
# | |
# Please use shebang as: | |
# #!/usr/bin/env cas -lm | |
# | |
# ------ | |
# Author: Shou Ya([email protected]) | |
# Date: Jan 23, 2012 | |
# Version: 1.0 | |
# | |
# [ -z "$CC" ] && { CC='gcc'} | |
CC="/usr/bin/gcc" | |
arg_1='' | |
arg_2='' | |
arg_3='' | |
function parse_arg { | |
until [ -z "$1" ]; do | |
[ -f "$1" ] && { | |
arg_2=$1; shift | |
arg_3="$@" | |
} || { | |
arg_1="$arg_1$IFS$1" | |
} | |
shift | |
done | |
} | |
parse_arg "$@" | |
# [ "$arg_2" = "" ] && arg_2="/dev/stdin" | |
tmpdir=`mktemp -d` | |
csource="$arg_2" | |
[ -z "$csource" ] && target=$tmpdir/tmp || target=$tmpdir/`basename $csource` | |
comp_log=$tmpdir/comp_log | |
comp_src=$tmpdir/source.c | |
function clean_up { | |
/bin/rm -rf $tmpdir | |
} | |
cat $csource > ${comp_src}_tmp | |
cat ${comp_src}_tmp | sed '1 s/#!.*//' > $comp_src | |
$CC -o $target $comp_src $arg_1 2>$comp_log | |
ret_code=$? | |
[ "$ret_code" != "0" ] && { | |
printf 'Compile Error: %s returns (%d)\n' "$CC" "$ret_code" | |
echo '-----------------------------' | |
cat $comp_log | |
echo '-----------------------------' | |
clean_up | |
exit 0 | |
} | |
# setup runtime environment | |
export CSC="1" | |
export CSC_VER="1.0" | |
[ -x $target ] || { | |
echo 'Target object cannot be executed.' | |
echo '----------------------------' | |
cat $comp_log | |
clean_up | |
exit 0 | |
} | |
$target $arg_3 | |
exit $? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment