Skip to content

Instantly share code, notes, and snippets.

@audunolsen
Last active December 31, 2017 16:56
Show Gist options
  • Save audunolsen/b24f6b81d3dea5c9e6b05fd5dee05125 to your computer and use it in GitHub Desktop.
Save audunolsen/b24f6b81d3dea5c9e6b05fd5dee05125 to your computer and use it in GitHub Desktop.
Shell script to compile and run c++ files with Make from the command line, call with $ cpp filename
####################
# C++ #
####################
# Function to compile and run c++ files from the command line, call with $ cpp filename
# Compiling and running c++ files with
# $ make filename && ./filename is overly verbose
# This function lessens on the typing required
function cpp {
if [ -z "$1" ]; then
echo "No filename provided."
else
# Compiler does not allow file extension, which may not be apparent to user,
# extension is therefore omitted in case it's written
file=$1; base=${file%.*}
# Compile and run
make $base && ./$base
fi
}
# NOTE! I've switched over to Z shell and discovered that zsh supports custom autocomplete functions.
# This suited this little script perfectly because it lessens on the typing required even more!
# Now just write "$ cpp" and tab away!
####################
# C++ #
####################
# Enable autocompletion of all existing .cpp files in current
# working directory for the cpp function's first argument
compdef _cpp cpp
_cpp () {
_arguments "1: C++ files:($( ls *.cpp ))"
}
# Function to compile and run c++ files from the command line, call with $ cpp filename
# Compiling and running c++ files with
# $ make filename && ./filename is overly verbose
# This function lessens on the typing required
function cpp {
if [ -z "$1" ]; then
echo "No filename provided."
else
# Compiler does not allow file extension, which may not be apparent to user,
# extension is therefore omitted in case it's written
file=$1; base=${file%.*}
# Horizontal divider line for visual aid making it easier to see where script starts
title="\n––– Running C++ script "; hr=$(printf '%*s' "${COLUMNS:-$(tput cols)}" '' | tr ' ' –)
# Compile and run
echo "\n" && make $base && echo $title${hr:23}"\n" && ./$base
fi
}
@luggasuggah
Copy link

Very useful, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment