pythoncparsingpycparser

How to find function name in function declarations with pycparser?


I found the following example to search for a specific function name like malloc, but I want to find all function names in function declarations of a C source file. So in the case of ReturnCode HashCreate(Hash** hash, unsigned int table_size) I'm looking for HashCreate and the line number. Since I'm not into Python and it seems pretty complicated, I'm asking how can I do this?

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)

Solution

  • The func_defs example does exactly what you are looking for:

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