如何使用libclang解析C ++标头?

我试图用libclang解析c ++头,但是解析器只解析类名-并将其类型显示为VarDec1。 当文件扩展名从.h更改为.cpp时,它可以正常工作。 经过几天的搜索,我找不到答案,有人可以帮我解决这个问题吗?

以下是parser.cpp:

#include <iostream>
#include <clang-c/Index.h>  // This is libclang.
using namespace std;

ostream& operator<<(ostream& stream,const CXString& str)
{
  stream << clang_getcString(str);
  clang_disposeString(str);
  return stream;
}

int main()
{
  CXIndex index = clang_createIndex(0,0);
  CXTranslationUnit unit = clang_parseTranslationUnit(
    index,"tt.h",nullptr,CXTranslationUnit_None);
  if (unit == nullptr)
  {
    cerr << "Unable to parse translation unit. Quitting." << endl;
    exit(-1);
  }

  CXCursor cursor = clang_getTranslationUnitCursor(unit);
  clang_visitChildren(
    cursor,[](CXCursor c,CXCursor parent,CXClientData client_data)
    {
      cout << "Cursor '" << (clang_getcursorSpelling(c)) << "' of kind '"
        <<(clang_getcursorKindSpelling(clang_getcursorKind(c))) << "'\n";
      return CXChildVisit_Recurse;
    },nullptr);

  clang_disposeTranslationUnit(unit);
  clang_disposeIndex(index);
  fgetc(stdin);
}

,以下是tt.h:

class MyClass
{
public:
  int field;
  virtual void method() const = 0;

  static const int static_field;
  static int static_method(int a1);
};

class MyClass2
{
public:
  int field;
  virtual void method() const = 0;

  static const string static_field;
  static int static_method(int a1,string a2);
};

我使用以下编译命令:

clang++ main.cpp -lclang

当文件扩展名为.h时: parse header

当文件扩展名为.cpp时: enter image description here

yinguang120 回答:如何使用libclang解析C ++标头?

libplang将

tt.h视为C文件,而不是C ++文件,因为文件类型严格基于扩展名。如果希望将其解析为C ++文件,则需要使用libclang识别为C ++扩展名的扩展名(我想.hh可以使用),或者需要使用command_line_args / num_command_line_args显式设置扩展名参数:

/* Untested */
const char *command_line_args[] = {"-x","c++",0};
CXTranslationUnit unit = clang_parseTranslationUnit(
    index,"tt.h",command_line_args,(sizeof command_line_args / sizeof *command_line_args) - 1,nullptr,CXTranslationUnit_None);

您可能还想从CXTranslationUnit中提取并打印诊断消息。可能,这将为您提供正在发生的事情的一个很好的线索。参见clang_getDiagnostic

本文链接:https://www.f2er.com/2965775.html

大家都在问