在寫C++控制台程序的時,如果使用Xcode或者Visual Studio之類的IDE,需要創建許多工程,會造成很多不便。有時,采用Vim或者Sublime text等編輯器編寫簡單的控制台程序能節省許多時間。但是,在編譯時,就必使用命令行編譯運行。這時,一個事先編寫好的shell腳本能大大縮短調試時間。
把下面的代碼復制並保存為xxx.sh文件,輸入要編譯的文件名(不包括后綴)和編譯選項(可選),即可運行(Linux或者MacOS系統)。
1 ##/bin/bash 2 echo "------------------compile.sh------------------" 3 4 name='' 5 sname='' 6 option='0' #0: debug | 1: normal 7 basepath=$(cd `dirname $0`; pwd) #獲取當前路徑 8 9 while [[ true ]]; do 10 #statements 11 read name option #獲取輸入 12 if [[ sname == '' && name == '' ]]; then 13 echo "Error: Wrong input" 14 continue 15 fi 16 17 if [[ -z "$name" ]]; then #沒有輸入的時候直接運行 18 echo "------------------runnning------------------" 19 $basepath/$sname.out 20 continue 21 fi 22 23 sname=$name 24 25 if [[ option -eq '0' ]]; then 26 echo "------------------compiling------------------" 27 if [[ -f "$basepath/$name.out" ]]; then 28 rm -f "$basepath/$name.out" 29 fi 30 g++ -o $basepath/$sname.out -D debug $basepath/$sname.cpp #編譯選項Debug 31 echo "------------------runnning------------------" 32 time $basepath/$sname.out #統計運行時間 33 fi 34 if [[ option -eq '1' ]]; then 35 echo "------------------compiling------------------" 36 if [[ -f "$basepath/$name.out" ]]; then 37 rm -f "$basepath/$name.out" 38 fi 39 g++ -o $basepath/$sname.out $basepath/$sname.cpp 40 echo "------------------runnning------------------" 41 $basepath/$sname.out 42 fi 43 done
程序在Debug時,不僅可以用#ifdef debug包含各種中間變量的輸出,還可以包括輸入輸出重定向。
#ifdef debug freopen("test.in","r",stdin);
freopen("test.out","w",stdout); #endif