2012-04-07 89 views
0

所以,我需要一个脚本需要一个文件路径作为输入编译&执行的代码(无论是C,C++,或Objective-C)。执行(在Mac OS X)通过bash脚本C/C++/Objective-C代码文件

我承认我不是一个BASH大师......所以,有没有更好的办法做到这一点?你会改变什么(以及为什么)?

这里是我的代码...


Ç

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 

回答

1

,如果你希望你的脚本将源代码编译为一个唯一的文件没有指定,或者如果你想要一个可执行的二进制文件被删除。也许你可以为ç使用类似:

#!/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 

,如果你确信你使用专门gcc编译,你可以使用它-x optiongcc -x c $input -o $binfile而不打扰复制输入到名为$cfile一个.c后缀文件。你也可能试图通过-Wall -Werror -g -Ogcc。而且您应该相信您以这种方式获取的文件(存在安全风险,例如,如果该文件包含system ("/bin/rm -rf $HOME");等)。

我不知道,如果你的MacOSX系统具有gcc(也许是clangcc)和tempfile工具,使临时文件名(也许是mktemp应不同调用)。