0

所以,我需要一个脚本,它将文件路径作为输入编译和执行代码(C、C++ 或 Objective-C)。

我承认我不是 BASH 大师……那么,有没有更好的方法呢?你会改变什么(为什么)?

这是我的代码...


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
4

1 回答 1

1

您没有指定是否希望脚本将源代码编译为唯一文件,或者是否希望删除该可执行二进制文件。也许你可以为C使用类似的东西:

#!/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 选项gcc -x c $input -o $binfile而不用费心将输入复制到一个.c名为$cfile. 您可能会想也传递-Wall -Werror -g -Ogcc. 而且您应该信任您以这种方式获得的文件(存在安全风险,例如,如果该文件包含system ("/bin/rm -rf $HOME");等)。

我不知道您的 MacOSX 系统是否有gcc(可能是clangcc)以及tempfile制作临时文件名的实用程序(可能mktemp应该以不同方式调用它)。

于 2012-04-09T15:33:51.350 回答