Get AST for C fragment using Clang?
2 answers
Maybe there are several ways to achieve this, but finally I got the following snippet and it looks simple enough to me:
//arguments to the compiler
std::unique_ptr <std::vector<const char*>> args(new std::vector<const char*>());
args->push_back("my_file.c");
//do the magic
ASTUnit *au = ASTUnit::LoadFromCommandLine(
&(*args)[0],
&(*args)[0] + args->size(),
IntrusiveRefCntPtr<DiagnosticsEngine>(
CompilerInstance::createDiagnostics(new DiagnosticOptions)),
StringRef()
);
//get the translation unit node
Declr *d = au->getASTContext().getTranslationUnitDecl();
Simple alternatives or suggestions for improving this are welcome.
+1
source to share
I don't have any ready-made copy-paste code, but the idea I used earlier is as follows:
Note that clang_parseTranslationUnit takes unsaved_files
one of the arguments. So the idea would be to provide the command line g++ main.cpp
and then provide the unsaved file with the name main.cpp
and content from your line.
-1
source to share