Recursive C header guard generator in Python
Posted: Wed Sep 07, 2011 10:16 pm
Here's a piece of Python code that I've put together today to help me automatically generate C header guards (I'm too tired of wasting my time by managing them manually, I don't want to do that any more!). Anyway, the script basically goes through the project structure and recursively scans header files for strings that begin with "FS_HEADER_", every each of them is then replaced by a new one that consists of two parts: a directory sequence and the header file itself.
For example, for '../fs/math/vector3.h' the final guard looks like this:
For example, for '../fs/math/vector3.h' the final guard looks like this:
Code: Select all
#define FS_HEADER__fs__math__vector3_h__GUARD
Code: Select all
#!/usr/bin/env python
# Recursive C header guard generator, ver 1.0
# (c) 2011 Filip STOKLAS (FipS), http://www.4FipS.com
# THIS CODE IS FREE - LICENSED UNDER THE MIT LICENSE
import sys
import os
import re
import fileinput
key = "FS_HEADER_"
def list_files_rec(root):
res = []
for cur_root, dirs, files in os.walk(root):
for file in files:
res.append(os.path.join(cur_root, file))
return res
def replace_str_in_file(file, cur, new):
for line in fileinput.FileInput(file, inplace=1):
line = re.sub(cur + r"(\w*)", new, line)
print line,
def main(root):
for file in list_files_rec(root):
if file[-2:] == ".h":
print file
cur = re.sub(r"[/\\]", "__", file)
cur = re.sub(r"\W+", "_", cur)
cur = cur.lstrip("_")
replace_str_in_file(file, key, key + "_" + cur + "__GUARD")
if __name__ == "__main__":
if len(sys.argv) == 2:
main(sys.argv[1])
else:
print "Usage: refresh_quards.py <dir>"