Search code examples
compiler-constructionclanglibclang

How do I get AST as string using libclang?


I need to transverse AST using libclang. All solutions I have found tell me to dump the AST in a .ast file and then create translationUnit with that file for transversing.

It would be great to be able to do the following: Generate AST for some code programmatically and then use CXUnsavedFile to create translationUnit with it


Solution

  • To avoid depending on AST dumped inside a file, clang_parseTranslationUnit can be used as follows

    CXTranslationUnit unit = clang_parseTranslationUnit(
    CXIndex index,
    "path to file with code", nullptr, 0,
    nullptr, 0,
    CXTranslationUnit_None);