2012-04-07 90 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應不同調用)。