【问题标题】:Why does libclang mis-parse C++ headers with a .h prefix?为什么 libclang 错误解析带有 .h 前缀的 C++ 标头?
【发布时间】:2019-12-06 02:41:10
【问题描述】:

我尝试使用 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, 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

【问题讨论】:

    标签: c++ c clang clang++ libclang


    【解决方案1】:

    tt.h 被 libclang 视为 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, 0,
        CXTranslationUnit_None);
    

    您可能还想从CXTranslationUnit 中提取和打印诊断消息。可能,这会给你一个很好的线索来了解正在发生的事情。见clang_getDiagnostic

    【讨论】:

    • 谢谢!它确实有效,并且诊断信息很有帮助! :)
    猜你喜欢
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2013-04-07
    • 2011-07-21
    • 2013-11-03
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多