Bash脚本来编译和运行C ++程序 [英] Bash script to compile and run C++ program
问题描述
我正在编写bash脚本来编译和运行C ++程序.这是我的剧本
I am writing a bash script to compile and run a C++ program. Here's my script
#!/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
文件.为此,我创建了一个变量来存储编译时错误消息.但是这种方法似乎不起作用,因为没有将输出重定向到变量.还有其他方法吗?
I don't want to run the a.out
file if the program fails to compile. To do so, I have created a variable to store compile time error message. But this approach doesn't seem to work, since the output is not being redirected to the variable. Is there any other way to do it?
这是对我有用的脚本
#!/bin/bash
PROG_NAME=$1
g++ -Werror $PROG_NAME
if [[ $? == 0 ]]; then
./a.out
fi
推荐答案
如果 g ++
失败,它将返回一个非零的返回值,可以使用Bash 检查该值.
命令:
If g++
fails it will return with a non-zero return-value which can be checked for with a Bash if
command:
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,因为它也将允许更复杂的项目.
A possibly better solution (IMO) is to learn how to use makefiles, as it will allow more complex projects as well.
这篇关于Bash脚本来编译和运行C ++程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!