【问题标题】:Shell script file for compiling and producing output of C file用于编译和生成 C 文件输出的 Shell 脚本文件
【发布时间】:2013-03-01 12:32:24
【问题描述】:

我编写了这个 .sh 文件来编译任何 c 源文件,所以当我运行它时,它会询问文件名,gcc 会编译它,然后运行可执行文件 a.out。

但是当 .c 文件中存在错误时,这将无法正常工作。它还表明 a.out 不存在。我不想要此错误消息(a.out 不存在),而只想打印为 .c 文件生成的错误消息..

这是脚本..

echo `clear`
echo enter file name
read FILE
gcc $FILE
./a.out
echo -e '\n'

【问题讨论】:

    标签: c unix gcc g++


    【解决方案1】:

    如果你在 shell 脚本中启用 abort-on-error,生活会轻松很多:

    #!/bin/sh
    set -eu # makes your program exit on error or unbound variable
    # ...your code here...
    

    【讨论】:

      【解决方案2】:

      使用内置规则作为脚本的替代方案,您可能希望使用make 作为手工脚本的替代方案。要编译file.c 并运行生成的可执行文件,您只需:

      make file && ./file
      

      如果您不知道,我强烈建议您查看make 实用程序,因为它可以大大简化您的工作。没有它,管理一个文件项目以外的任何东西都会变得非常讨厌。

      【讨论】:

        【解决方案3】:

        您可以链接编译和执行命令:

        echo `clear`
        echo enter file name
        read FILE
        gcc $FILE && ./a.out
        echo -e '\n'
        

        这里,如果 gcc 失败,shell 将丢弃 ./a.out 命令。

        【讨论】:

          【解决方案4】:

          你也可以用双引号保护文件名:

          #! /bin/bash
          clear
          echo -n "Enter file name: "
          read FILE
          gcc -Wall -W "$FILE" && ./a.out
          echo
          

          【讨论】:

          • 谢谢你提醒我那些-Wall -W...我有段时间忘记用了...
          【解决方案5】:

          我希望这就是你正在寻找的它只需要这个命令:

          ./compile executableName myCProgram.c -lm

          您可以将更多的 C 文件放在彼此前面,并在行尾添加更多库,并且 executableName 不需要 .exe

          #!/bin/bash
          args="$@"
          quant=$#
          
          #Copies in case you need the -lm(math library) params
          biblio=${args#*-}
          #grabs all params except the first one which should be the name of the executable
          firstCommand=${*:2:${#args}}
          #Remove the "-lm -lc" from firstCommand
          firstCommand=${firstCommand%%-*}
          
          printf "\nEXECUTING: gcc -W -Wall -c $firstCommand\n"
          
          #Creates the object file ".o"
          gcc -W -Wall -c $firstCommand
          
          #Convert the files names from example.c to example.o
          args=${args//.c/.o}
          printf "\nEXECUTING: gcc -o $args\n\n"
          
          #Creates the executable
          gcc -o $args
          
          printf "\n**Now execute comand: ./$1  **\n\n"
          

          【讨论】:

            猜你喜欢
            • 2012-11-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-11-01
            相关资源
            最近更新 更多