Last active
December 25, 2015 16:59
-
-
Save panzi/7010082 to your computer and use it in GitHub Desktop.
Run some C code. -p to simply pass a printf format string and args, -iFILE to include FILE, -I -L -l -E -S -D and -O will be passed as such to gcc.Examples: CFLAGS=-std=c99 cexpr.sh 'puts("hello world");'; cexpr.sh -imath.h -lm -p '%g' 'log2(8)'
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
#!/bin/bash | |
do_printf=off | |
incs="" | |
flags="$CFLAGS" | |
only_preproc=off | |
no_asm=off | |
if [ "$CC" = "" ]; then | |
CC=gcc | |
fi | |
while getopts i:pI:L:l:W:O:D:SEf: opt "$@"; do | |
case $opt in | |
I|L|l|W|O|D) | |
flags="$flags -$opt$OPTARG" | |
;; | |
f) | |
flags="$flags $OPTARG" | |
;; | |
S) | |
no_asm=on | |
;; | |
E) | |
only_preproc=on | |
;; | |
p) | |
do_printf=on | |
;; | |
i) | |
incs="$incs | |
#include \"$OPTARG\"" | |
;; | |
\?) | |
echo "Invalid option: -$OPTARG" >&2 | |
exit 1 | |
;; | |
esac | |
done | |
shift $((OPTIND - 1)) | |
if [ "$do_printf" = "on" ]; then | |
fmt="$1" | |
shift | |
args="" | |
for arg in "$@"; do | |
args="$args, $arg" | |
done | |
stmts=" | |
printf(\"$fmt\\n\"$args);" | |
else | |
stmts="" | |
for stmt in "$@"; do | |
stmts="$stmts | |
$stmt;" | |
done | |
fi | |
args="-x c -Wall -Werror $flags -" | |
{ | |
cat << EOF | |
#include <stdlib.h> | |
#include <stdio.h> | |
$incs | |
int main (int argc, char *argv[]) {$stmts | |
return 0; | |
} | |
EOF | |
} | if [ "$only_preproc" = on ]; then | |
"$CC" $args -E -o - | |
elif [ "$no_asm" = on ]; then | |
"$CC" $args -S -o - | |
else | |
tmp=/tmp/cexpr.$$.out | |
"$CC" $args -o $tmp && { | |
$tmp | |
code=$? | |
rm -f $tmp | |
exit $code | |
} | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment