Skip to content

Instantly share code, notes, and snippets.

@dmikushin
Created January 2, 2024 12:24
Show Gist options
  • Save dmikushin/7ea6efc2f98bef86f0f9907c96f02ed6 to your computer and use it in GitHub Desktop.
Save dmikushin/7ea6efc2f98bef86f0f9907c96f02ed6 to your computer and use it in GitHub Desktop.
Minify C++ code
import re
import sys
def minify_cpp_code(code):
# Remove comments:
# Turn single-line comments into multi-line comments
code = re.sub(re.compile(r'//(.*?)\n'), '/*\\1*/', code)
# Remove multi-line comments
code = re.sub(re.compile(r'/\*.*?\*/', re.DOTALL), '', code)
# Preprocessing directives must remain on separate lines.
# Add a special marker to the end of each #directive
# to insert back newlines later
code = re.sub(re.compile(r'(#.*)'), '\\1\255', code)
# Remove newlines and excess whitespace
code = re.sub(re.compile(r'\s+'), ' ', code)
code = re.sub(re.compile(r'\s*;\s*'), ';', code)
code = re.sub(re.compile(r'\s*{\s*'), '{', code)
code = re.sub(re.compile(r'\s*}\s*'), '}', code)
code = re.sub(re.compile(r'\s*\(\s*'), '(', code)
code = re.sub(re.compile(r'\s*\)\s*'), ')', code)
code = re.sub(re.compile(r'\s*,\s*'), ',', code)
# Restore newlines after each #directive
code = re.sub(re.compile('(#[^#]+)\255'), '\n\\1\n', code)
# Remove empty and whitespace lines
code = re.sub(re.compile(r'\n\s*\n'), '\n', code)
return code.strip()
'''
# Example usage:
cpp_code = """
#include <iostream>
// This is a comment
int main() {
/* This is a
multi-line comment */
std::cout << "Hello, World!" << std::endl; // Print Hello, World!
return 0;
}
"""
minified_code = minify_cpp_code(cpp_code)
print(minified_code)
'''
if __name__ == '__main__':
with open(sys.argv[1], 'r') as file:
file_contents = file.read()
print(minify_cpp_code(file_contents))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment