使用Shell脚本编译运行C++源码 输入输出重定向

时间:2023-03-09 18:34:06
使用Shell脚本编译运行C++源码 输入输出重定向

  在写C++控制台程序的时,如果使用Xcode或者Visual Studio之类的IDE,需要创建许多工程,会造成很多不便。有时,采用Vim或者Sublime text等编辑器编写简单的控制台程序能节省许多时间。但是,在编译时,就必使用命令行编译运行。这时,一个事先编写好的shell脚本能大大缩短调试时间。 

  把下面的代码复制并保存为xxx.sh文件,输入要编译的文件名(不包括后缀)和编译选项(可选),即可运行(Linux或者MacOS系统)。

 ##/bin/bash
echo "------------------compile.sh------------------" name=''
sname=''
option='' #: debug | : normal
basepath=$(cd `dirname $`; pwd) #获取当前路径 while [[ true ]]; do
#statements
read name option #获取输入
if [[ sname == '' && name == '' ]]; then
echo "Error: Wrong input"
continue
fi if [[ -z "$name" ]]; then #没有输入的时候直接运行
echo "------------------runnning------------------"
$basepath/$sname.out
continue
fi sname=$name if [[ option -eq '' ]]; then
echo "------------------compiling------------------"
if [[ -f "$basepath/$name.out" ]]; then
rm -f "$basepath/$name.out"
fi
g++ -o $basepath/$sname.out -D debug $basepath/$sname.cpp #编译选项Debug
echo "------------------runnning------------------"
time $basepath/$sname.out                      #统计运行时间
fi
if [[ option -eq '' ]]; then
echo "------------------compiling------------------"
if [[ -f "$basepath/$name.out" ]]; then
rm -f "$basepath/$name.out"
fi
g++ -o $basepath/$sname.out $basepath/$sname.cpp
echo "------------------runnning------------------"
$basepath/$sname.out
fi
done

  程序在Debug时,不仅可以用#ifdef debug包含各种中间变量的输出,还可以包括输入输出重定向。

#ifdef debug
  freopen("test.in","r",stdin);
  freopen("test.out","w",stdout);
#endif