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.cpp
或 run test.c
即可运行
注:复制到vim中时,如果出现格式错误,先
:set paste
一下,之后再粘贴