Created
April 29, 2022 05:22
-
-
Save anglyan/7cd72ecf7b9aa563910ef5b738ca5970 to your computer and use it in GitHub Desktop.
Simple code to automatically extract dependencies from C/C++ files and generate Make target rules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Simple code to automatically extract dependencies from C/C++ files and | |
generate Make target rules | |
""" | |
def get_deps(filename): | |
dep_set = set() | |
with open(filename, 'r') as f: | |
for line in f: | |
tokens = line.strip().split() | |
if len(tokens) > 0: | |
if tokens[0] == "#include": | |
if tokens[1].startswith('"'): | |
dep_set.add(tokens[1][1:-1]) | |
len_ext = len(filename.split(".")[-1]) | |
headername = filename[:-len_ext]+"h" | |
if headername in dep_set: | |
try: | |
with open(headername, 'r') as f: | |
for line in f: | |
tokens = line.strip().split() | |
if len(tokens) > 0: | |
if tokens[0] == "#include": | |
if tokens[1].startswith('"'): | |
dep_set.add(tokens[1][1:-1]) | |
except FileNotFoundError: | |
pass | |
return dep_set | |
def rule_generator(filename, base_rule=r"${CXX} ${CXXFLAGS} -c "): | |
dep_set = get_deps(filename) | |
len_ext = len(filename.split(".")[-1]) | |
objectname = filename[:-len_ext]+"o" | |
target = "{} : {} ".format(objectname, filename) + " ".join(dep_set) | |
rule = "\t" + base_rule + filename | |
return target, rule | |
if __name__ == "__main__": | |
import glob | |
for filename in glob.glob("*.cpp"): | |
target, rule = rule_generator(filename) | |
print(target) | |
print(rule) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment