为什么 libclang 会错误解析带有 .h 前缀C++标头?

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

本文关键字:前缀 C++ 标头 libclang 错误 误解 为什么      更新时间:2023-10-16

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

以下是解析器.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 时: 解析标头

当文件扩展名为.cpp时: 在此处输入图像描述

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。