【问题标题】:Execute C/C++/Objective-C code file via BASH script (on Mac OS X)通过 BASH 脚本执行 C/C++/Objective-C 代码文件(在 Mac OS X 上)
【发布时间】:2012-04-07 11:43:38
【问题描述】:

所以,我需要一个将文件路径作为输入编译并执行代码(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

【问题讨论】:

    标签: macos bash gcc g++ clang


    【解决方案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 option 用作gcc -x c $input -o $binfile,而不必费心将输入复制到一个名为.c 的后缀为$cfile 的文件中。你也可以将-Wall -Werror -g -O 传递给gcc。而且您应该信任您以这种方式获得的文件(存在安全风险,例如,如果该文件包含system ("/bin/rm -rf $HOME"); 等)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多