如何使用 pycparser 在函数声明中查找函数名称?

How to find function name in function declarations with pycparser?

我找到了以下示例来搜索特定的函数名称,如 malloc,但我想在 C 源文件的函数声明中查找所有函数名称。所以在 ReturnCode HashCreate(Hash** hash, unsigned int table_size) 的情况下,我正在寻找 HashCreate 和行号。由于我不喜欢 Python 而且它看起来很复杂,我想问一下我该怎么做?

from __future__ import print_function
import sys

sys.path.extend(['.', '..'])

from pycparser import c_parser, c_ast, parse_file

class FuncCallVisitor(c_ast.NodeVisitor):
    def __init__(self, funcname):
        self.funcname = funcname

    def visit_FuncCall(self, node):
        if node.name.name == self.funcname:
            print('%s called at %s' % (self.funcname, node.name.coord))


def show_func_calls(filename, funcname):
    ast = parse_file(filename, use_cpp=True,
                     cpp_path='clang',
                     cpp_args=['-E'])
    v = FuncCallVisitor(funcname)
    v.visit(ast)


if __name__ == "__main__":
    if len(sys.argv) > 2:
        filename = sys.argv[1]
        func = sys.argv[2]
    else:
        filename = 'hash.c'
        func = 'malloc'

    show_func_calls(filename, func)

func_defs 示例完全符合您的要求:

# Using pycparser for printing out all the functions defined in a
# C file.