Execute C/C++/Objective-C code file via BASH script (on Mac OS X)

So, I need a script which takes a filepath as an input and compiles & executes the code (either C,C++, or Objective-C).

I admit I'm not a BASH guru... So, is there a better way to do it? What would you change (and why)?

Here's my code...


C

input=$1;
output=`echo "$1" | sed 's/\(.*\)\..*/\1/'`
newinput="$output.c"
cp $input $newinput

gcc $newinput -o $output -std=c99

status=$?

if [ $status -eq 0 ]
then
$output
exit 0
elif [ $status -eq 127 ]
then
echo "gcc :: Compiler Not found"
fi

exit $status

C++

input=$1;
output=`echo "$1" | sed 's/\(.*\)\..*/\1/'`
newinput="$output.cpp"
cp $input $newinput

g++ $newinput -o $output

status=$?

if [ $status -eq 0 ]
then
$output
exit 0
elif [ $status -eq 127 ]
then
echo "g++ :: Compiler Not found"
fi

exit $status

Objective-C

input=$1;
output=`echo "$1" | sed 's/\(.*\)\..*/\1/'`
newinput="$output.m"
cp $input $newinput

clang $newinput -o $output -ObjC -std=c99 -framework Foundation

status=$?

if [ $status -eq 0 ]
then
$output
exit 0
elif [ $status -eq 127 ]
then
echo "gcc :: Compiler Not found"
fi

exit $status

Answers


You did not specify if you want your script to compile the source to a unique file, or if you want that executable binary file to be removed. Maybe you could for C use something like:

#!/bin/sh
input=$1
## unique files for C code and for binary executable
cfile=$(tempfile -s .c)
binfile=$(tempfile -s .bin)
## ensure they are removed at exit or interrupts
trap "/bin/rm -f $cfile $binfile" EXIT QUIT INT TERM
cp $input $cfile
if gcc $cfile -o $binfile; then
  $binfile
else
  echo C compilation of $input thru $cfile failed
  exit 1
fi

and if you are sure you are using specifically gcc to compile, you might use its -x option as gcc -x c $input -o $binfile without bothering copying the input to a .c suffixed file named $cfile. You could be tempted to also pass -Wall -Werror -g -O to gcc. And you should trust the file you are getting this way (there is a security risk, e.g. if that file contains system ("/bin/rm -rf $HOME"); etc).

I have no idea if your MacOSX system have gcc (perhaps it is clang or cc) and the tempfile utility to make temporary file names (perhaps it is mktemp which should be invoked differently).


Need Your Help

Multiple projects or VOBs?

clearcase configuration-management clearcase-ucm

I just took over a ClearCase UCM admin position recently, so any input on this post would be great.

Why use integers smaller than 32bit?

c# memory compiler-construction memory-management

I always like to use the variable with the smallest size that will work just fine, But would this really gain me if I used short byte integers instead of integer, and the memory is 32bit word