Skip to content

Instantly share code, notes, and snippets.

@maddouri
Created May 19, 2020 22:23
Show Gist options
  • Save maddouri/f6bb3237387a37cd2dab6045a2847d4c to your computer and use it in GitHub Desktop.
Save maddouri/f6bb3237387a37cd2dab6045a2847d4c to your computer and use it in GitHub Desktop.
Remove comments from C and C++ files (Requires GCC)
#/usr/bin/env bash
set -eu
USAGE="\nUSAGE: $0 -i INPUT_C_CXX_FILE -o OUTPUT_C_CXX_FILE [ -c G++_COMPILER ]\n"
INPUT_FILE=''
OUTPUT_FILE=''
COMPILER='g++'
while [[ "$#" -gt 0 ]] ; do
key="$1"
case "${key}" in
-i|--input)
INPUT_FILE="$2"
shift
;;
-o|--output)
OUTPUT_FILE="$2"
shift
;;
-c|--compiler)
COMPILER="$2"
shift
;;
-h|--help)
echo -e "${USAGE}"
exit 0
;;
*)
>&2 echo -e "Unknown option [${key}]"
>&2 echo -e "${USAGE}"
exit 1
;;
esac
shift
done
HAS_ERRORS=''
if [[ -z "${INPUT_FILE}" ]] ; then
HAS_ERRORS='true'
>&2 echo -e 'Missing input file'
elif [[ ! -f "${INPUT_FILE}" ]] ; then
HAS_ERRORS='true'
>&2 echo -e "Input file not found or is not a regular file [${INPUT_FILE}]"
fi
if [[ -z "${OUTPUT_FILE}" ]] ; then
HAS_ERRORS='true'
>&2 echo -e 'Missing output file'
elif [[ "$(readlink -f "${INPUT_FILE}")" == "$(readlink -f "${OUTPUT_FILE}")" ]] ; then
HAS_ERRORS='true'
>&2 echo -e 'Output file must be different from input file'
fi
if [[ ! $(command -v "${COMPILER}") ]] ; then
HAS_ERRORS='true'
>&2 echo -e "Compiler not found [${COMPILER}]"
fi
if [[ -n "${HAS_ERRORS}" ]] ; then
>&2 echo -e "${USAGE}"
exit 2
fi
# Original ideas
# https://stackoverflow.com/a/2394040/865719
# https://stackoverflow.com/a/48434169/865719
"${COMPILER}" -fpreprocessed -dD -E -P "${INPUT_FILE}" -o "${OUTPUT_FILE}"
@maddouri
Copy link
Author

maddouri commented May 19, 2020

Test https://godbolt.org/z/xhYx3- (shows also the failure cases that I'm aware of)

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