Linux下如何快速编译运行C++程序(run脚本)

linux下如何快速编译运行C/C++程序(run脚本)

前言:

正常系统里安装完g++后,并写好一个C++程序如 test.cpp 后

编译 :g++ test.cpp

运行 :./a.out

需要执行两步

如何将两步合并为一步,并兼容C语言程序呢?那就需要自己手动实现一个脚本程序来简化操作步骤。

  • which g++ 得到一个g++所在的目录 (环境变量) 如我的主机得到 /usr/bin/g++
luzelin@ubuntu test % which g++
/usr/bin/g++
  • cd /usr/bin 切换到g++所在的目录
  • sudo touch run 建立一个空的run文件
  • sudo chmod 777 run 修改run文件的权限(拉满)
  • sudo vim run 打开run文件,并把下面代码复制进去。之后保存退出~
#!/bin/bash
CC="gcc -lm -Wall"
GPP="g++ -std=c++11 -Wall"

function CheckType() {
    type=`echo $1 | tr "." "\n" | tail -1`
    if [[ ${type} == "c" ]]; then
        return 0
    elif [[ ${type} == "cpp" ]]; then
        return 1
    elif [[ ${type} == "sh" ]]; then
        return 2
    elif [[ ${type} == "py" ]]; then
        return 3
    else
        exit
    fi
}

File=$1
Args=($@)
unset Args[0]

OutFile=`echo ${File} | tr "." "\n" | head -1 | tr "\n" "."`

CheckType ${File}
re=$?

if [[ ${re} -eq 0 ]]; then
    ${CC} ${File} -o ${OutFile}exe && time ./${OutFile}exe ${Args[*]} && rm -f ${OutFile}exe
elif [[ ${re} -eq 1 ]]; then
    ${GPP} ${File} -o ${OutFile}exe && time ./${OutFile}exe ${Args[*]}&& rm -f ${OutFile}exe
elif [[ ${re} -eq 2 ]]; then
    time bash ${File} ${Args[*]}
else
    time python3 ${File} ${Args[*]}
fi

现在写一个C/C++程序后,可以执行 run test.cpprun test.c 即可运行

注:复制到vim中时,如果出现格式错误,先 :set paste 一下,之后再粘贴

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值