使用Shell腳本編譯運行C++源碼 輸入輸出重定向

  在寫C++控制檯程序的時,若是使用Xcode或者Visual Studio之類的IDE,須要建立許多工程,會形成不少不便。有時,採用Vim或者Sublime text等編輯器編寫簡單的控制檯程序能節省許多時間。可是,在編譯時,就必使用命令行編譯運行。這時,一個事先編寫好的shell腳本能大大縮短調試時間。 shell

  把下面的代碼複製並保存爲xxx.sh文件,輸入要編譯的文件名(不包括後綴)和編譯選項(可選),便可運行(Linux或者MacOS系統)。bash

 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
相關文章
相關標籤/搜索