S.C*_*.C. 2 c c++ clang clang++ libclang
我尝试使用 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);
}
Run Code Online (Sandbox Code Playgroud)
以下是 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);
};
Run Code Online (Sandbox Code Playgroud)
我使用以下编译命令:
clang++ main.cpp -lclang
Run Code Online (Sandbox Code Playgroud)
当文件扩展名为.h时: 解析头
当文件扩展名是.cpp时: 在此处输入图像描述
tt.hlibclang 认为是 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);
Run Code Online (Sandbox Code Playgroud)
您可能还想从CXTranslationUnit. 也许,这会让你对正在发生的事情有一个很好的线索。请参阅clang_getDiagnostic。
| 归档时间: |
|
| 查看次数: |
2299 次 |
| 最近记录: |