我试图用 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 时:解析头
当文件扩展名为 .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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句