c++parsingclanglibclang

How to parse FieldDecl with libclang?


Using the example Clang lambda, I'm trying to parse a c++ header file. The problem is, I'm unsure how to parse a CXCursor_FieldDecl for the type and name of a member field of a class.

clang_visitChildren(cursor,                                                 
    [](CXCursor c, CXCursor parent, CXClientData client_data) {             
                                                                            
        if (clang_getCursorKind(c) == CXCursor_FieldDecl) {            
            std::cout << clang_getCursorKindSpelling(clang_getCursorKind(c))
                << " " << clang_getCursorSpelling(c) << ";\n";
        }                                                                   
                                                                            
        return CXChildVisit_Recurse;                                        
    }, nullptr);
    

The above will print out:

FieldDecl varA;
FieldDecl varB;
FieldDecl varC;

What I'm looking for is:

int    varA;
double varB;
string varC;

Any thoughts on how to parse a FieldDecl for type and name of member field?


Solution

  • The name of the variable is the spelling of the cursor. The type of the variable is the spelling of the cursor type. You may want to look at the documentation for clang_getCanonicalType as well.

    std::string name = spelling(c);
    std::string type = spelling(clang_getCursorType(c));