1

I want to parse c source code for extracting variables and functions from it. Is there any library available for this purpose?

I tried to achieve it through query language available in tree-sitter parser generator but when I run the program it says undefined reference to the query functions used in the file even I have included the header file (api.h) containing query functions. I tried to resolve these errors but couldn't so looking for some other library which can serve the purpose.

Ansa
  • 11
  • 2

1 Answers1

1

It's better to do it with Clang (e.g. cindex Python API).

For example, to find all function definitions in a translation unit:

#!/usr/bin/env python3

import sys
import clang.cindex

def find_functions(node):
    if node.kind == clang.cindex.CursorKind.FUNCTION_DECL:
        nm = node.spelling
        print(f"Function {nm}")
    else:
        for c in node.get_children():
            find_functions(c)

index = clang.cindex.Index.create()
tu = index.parse(sys.argv[1])
print('Translation unit:', tu.spelling)
find_functions(tu.cursor)
SK-logic
  • 9,605
  • 1
  • 23
  • 35