Advertisement
lxli

Build and Run C++ with Time and Exit Code

Sep 25th, 2023 (edited)
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.30 KB | None | 0 0
  1. # Build and run a C++ file, showing execution time and exit code.
  2. # Usage: cpprun srcfile [arg2] ... [arg99] [<file.in] [>file.out]
  3. # Example: cpprun code.cpp <file.in >file.out  (specifying .cpp is optional)
  4. cpprun() {
  5.   basepath="${1%%.*}"  # Strip extension.
  6.   [[ "$1" == "$basepath" ]] && srcpath="$basepath".cpp || srcpath=$1
  7.   # Change the build command and arguments below as you like it it.
  8.   # On Mac, `gcc` is likely just a clang shim and won't have bits/stdc++.h.
  9.   # Install the real GCC with `brew install gcc` and invoke with `g++-13`.
  10.   g++-13 "$srcpath" -o "$basepath" -O3 -std=gnu++17 -Wl,-stack_size -Wl,20000000 -Wall -Wno-variadic-macros
  11.   status=$?
  12.   if [ $status -eq 0 ]; then
  13.     # On Mac, must run `brew install coreutils`
  14.     [[ "$(uname)" == "Darwin" ]] && start=$(gdate +%s.%N) || start=$(date +%s.%N)
  15.     # Check if argument is a path, else run in current directory.
  16.     [[ "$basepath" == *\/* ]] && "$basepath" "${@:2:99}" || ./"$basepath" "${@:2:99}"
  17.     status=$?
  18.     [[ "$(uname)" == "Darwin" ]] && end=$(gdate +%s.%N) || end=$(date +%s.%N)
  19.     runtime=$(python -c "print('{0:.0f}m {1:.3f}s'.format(*divmod(${end}-${start},60)))")
  20.     echo "Finished in $runtime with exit code ${status}." >&2
  21.     return $status
  22.   else
  23.     echo "Build failed" >&2
  24.     return $status
  25.   fi
  26. }
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement