Writing a bash script to quickly compile C++ code for Codeforces and CSES

JohnWatsonAtBaker
2 min readJan 17, 2021

I’ve started doing introductory Codeforces and CSES problems recently. The language I picked is C++. The typical workflow is to write the script, compile it, run it with the example input file and check the output. I wanted to make this whole process more automatic.

Hence the following shell script:

#!/bin/bash# make sure we have two arguments
if [ “$#” -ne 2 ]; then
echo “Need 2 parameters, got $#”
exit 1
fi
# get the file path
src_file_path=”$PWD/$1"
run_file_path=”$PWD/a.out”
in_file_path=”$PWD/$2"
if [ ! -f “$src_file_path” ]; then
echo “$src_file_path does not exist”
exit 1
fi
if [ ! -f “$in_file_path” ]; then
echo “$in_file_path does not exist”
exit 1
fi
# remove the old
if [ -f “$run_file_path” ]; then
rm $run_file_path
fi
# compile
clang++ $src_file_path -o $run_file_path -std=c++17 -O2 -Wall
# run
$run_file_path < $in_file_path

For instance, if I want to test my solution to the first problem in CSES: weird algorithm, all I need to do is type:

./mr.sh weird_algorithm.cpp in

Of course, there are some condition checks in the scripts:

  • make sure we have two arguments and they all exist
  • use the complete path (assuming the source code and the input are in the same directory)
  • remove the old executable if any (this is for the case when clang++ fails and the executable from a previous successful compilation gets used)

The last step is to make this more command-like. I am using zsh on a mac, so I just went in ~/.oh-my-zsh/custom and added a new file with the following:

# You can put files here to add functionality separated per file, which
# will be ignored by git.
# Files on the custom/ directory will be automatically loaded by the init
# script, in alphabetical order.
# For example: add yourself some shortcuts to projects you often work on.
#
alias mr=’~/Development/Practice/mr.sh’

Now it became:

mr weird_algorithm.cpp in

--

--