为什么 libclang mis-parse C++ headers 带有 .h 前缀?

Why does libclang mis-parse C++ headers with a .h prefix?

我试图用 libclang 解析 c++ header,但解析器只解析了 class 名称 - 并将其类型显示为 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, 0,
    nullptr, 0,
    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

tt.h 被 libclang 认为是 C 文件,而不是 C++ 文件,因为文件类型严格基于扩展名。如果你希望它被解析为 C++ 文件,你需要使用 libclang 识别为 C++ 扩展的扩展(我想 .hh 可以工作),或者你需要使用 [=19 显式设置扩展=]参数:

/* 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, 0,
    CXTranslationUnit_None);

您可能还想从 CXTranslationUnit 中提取并打印诊断消息。也许,这会给你一个很好的线索,让你知道发生了什么。参见 clang_getDiagnostic