Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@napthink
Last active January 22, 2017 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save napthink/2d5d8b5a8028761156288280e31c370c to your computer and use it in GitHub Desktop.
Save napthink/2d5d8b5a8028761156288280e31c370c to your computer and use it in GitHub Desktop.
Cのプログラムを手軽にコンパイル&実行するシェルスクリプト
#!/bin/bash
# 実行ファイルの出力先ディレクトリ
out_dir=~/bin
compiler=gcc
usage="usage: $0 [FILE] [ARGUMENTS]"
if [ $# = 0 ]; then
echo "$usage" >&2
exit
fi
# 第一引数をソースファイルとする
source_file=$1
shift
# ファイルの存在チェック
if [ ! -e $source_file ]; then
echo "file does not exist." >&2
exit 1
fi
# 出力ファイルのパスを設定
filename=$(basename $source_file)
out=$out_dir/${filename%.*}
# 拡張子をもとにコンパイラを設定
extension=${filename##*.}
if [ $extension = "cpp" ]; then
compiler=g++
fi
# 前回コンパイル時よりソースファイルが更新されていなければコンパイルしない
if [ -e $out ] && [ $out -nt $source_file ]; then
echo "$out is up to date." >&2
else
# コンパイル
echo "$compiler $1 -o $out" >&2
$compiler $source_file -o $out
# コンパイルエラー時は終了
if [ $? != 0 ]; then
echo "failed to compile." >&2
exit 1
fi
fi
# 実行
echo "$out $*" >&2
$out $*
echo "exit status: $?" >&2