zoukankan      html  css  js  c++  java
  • 使用Shell脚本编译运行C++源码 输入输出重定向

      在写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
  • 相关阅读:
    (第七周)评论alpha发布
    (第六周)工作总结
    (第六周)团队项目6
    (第六周)团队项目5
    (第六周)团队项目4
    (第六周)团队项目燃尽图
    (第六周)团队项目3
    (第六周)课上Scrum站立会议演示
    Java第二次作业第五题
    Java第二次作业第四题
  • 原文地址:https://www.cnblogs.com/SaltyFishQF/p/10288125.html
Copyright © 2011-2022 走看看