我需要分析一些 C 文件并打印出所有找到的#define。使用正则表达式并不难(例如)
def with_regexp(fname):
    print("{0}:".format(fname))
    for line in open(fname):
        match = macro_regexp.match(line)
        if match is not None:
            print(match.groups())
但是例如它不处理例如多行定义。
在 C 中有一种很好的方法,例如
gcc -E -dM file.c
问题是它返回所有#defines,而不仅仅是给定文件中的那个,而且我没有找到任何仅使用给定文件的选项..
有什么提示吗?谢谢
编辑:这是过滤掉不需要的定义的第一个解决方案,只需检查定义的名称实际上是原始文件的一部分,不完美但似乎工作得很好..
def with_gcc(fname):
    cmd = "gcc -dM -E {0}".format(fname)
    proc = Popen(cmd, shell=True, stdout=PIPE)
    out, err = proc.communicate()
    source = open(fname).read()
    res = set()
    for define in out.splitlines():
        name = define.split(' ')[1]
        if re.search(name, source):
            res.add(define)
    return res