0

I am developing a windows C++ tool to analyze and mutate C code. I need help to use libClang or preferably libTooling get a list of C function declarations from a source tree of C files (translation units) with their headers. Eventually, I would like to transform the C files to add instrumentation points.

I need a good starting point example. I started with an example from AST matchers and Clang refactoring tools. This seems like a reasonable jumping off point but I don't know how to actually get the list of function names back to where I can assign them to string variables that I can use in my application.

I think ASTMatchers would be the preferred approach to tackle this problem. Shown below I created a simple clang-query example to find all function declarations in a single 'test.c' translation unit. The simple query clang-query> m functionDecl(). expression returned a list of underligned function declarations including the return type and arguments. AST matchers can be easily created from simple clang-query scripts as I understand.

Here is the simple clang-query example of what I would like to achieve in C++: Using a test file 'test.cpp':

// example code
int testFn0(const int* pa, int *pb) {
    return 3;
}

void testFn(const int* pa, int *pb) {
    int t = 0;
    bool a = true;
    bool b = true;
    bool c = true;
    bool d = true;
    if (a && b || !(c ^ d)) {
        t = 0;
    }
}

Then using clang-query

~/tools$ clang-query test.c --

clang-query> m functionDecl()

Match #1:

/home/jcoffey/tools/test.cpp:3:1: note: "root" binds here
int testFn0(const int* pa, int *pb) {
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Match #2:

/home/tools/test.cpp:7:1: note: "root" binds here
void testFn(const int* pa, int *pb) {
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2 matches.
johnco3
  • 2,401
  • 4
  • 35
  • 67
  • 1
    This seems like it is very nearly a duplicate of [How to find method declarations in LibTooling?](https://stackoverflow.com/questions/74764286/how-to-find-method-declarations-in-libtooling/76742519). The solution I posted there seems like it would do what you want, except you'd want to globally replace "CXXMethodDecl" with "FunctionDecl" to report all functions rather than only methods. – Scott McPeak Aug 06 '23 at 18:31

0 Answers0