首页 > 解决方案 > 用于编译和运行 C++ 程序的 Bash 脚本

问题描述

我正在编写一个 bash 脚本来编译和运行 C++ 程序。这是我的脚本

#!/bin/bash
PROG_NAME=$1
output=$(g++ $PROG_NAME)  #redirect the error to a variable
echo $output              #show the error on stdout
if [$output = ""] 
then
    ./a.out
fi

a.out如果程序无法编译,我不想运行该文件。为此,我创建了一个变量来存储编译时错误消息。但是这种方法似乎不起作用,因为输出没有被重定向到变量。还有其他方法吗?

编辑

这是对我有用的脚本

#!/bin/bash
PROG_NAME=$1
g++ -Werror $PROG_NAME
if [[ $? == 0 ]]; then
    ./a.out
fi

标签: linuxbash

解决方案


如果g++失败,它将返回一个非零返回值,可以使用 Bashif命令检查:

output=$(g++ $PROG_NAME 2>&1)
if [[ $? != 0 ]]; then
    # There was an error, display the error in $output
    echo -e "Error:\n$output"
else
    # Compilation successfull
    ./a.out
fi

一个可能更好的解决方案 (IMO) 是学习如何使用 makefile,因为它也将允许更复杂的项目。


推荐阅读