1

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)

1 Answer 1

2

The func_defs example does exactly what you are looking for:

# Using pycparser for printing out all the functions defined in a
# C file.
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, exactly what I needed. Is it possible to tell pycparser to ignore header files? It's a little inconvenient to add all header files in a file like this.
@JohnnyFromBF: read eli.thegreenplace.net/2015/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.