为什么 libclang 会错误解析带有 .h 前缀C++标头?
Why does libclang mis-parse C++ headers with a .h prefix?
我试图用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。
相关文章:
- 编译器如何在前缀和 postix 运算符之间进行区分?
- 查找带有 Anaconda cmake 前缀的 boost-python3
- 迭代器类的重载前缀增量运算符会引发分段错误
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 生成前缀位掩码
- 定义宏以将前缀 0x 添加到十六进制字符串文本
- CMake 错误 - 目标 foo INTERFACE_SOURCES属性包含在源目录中以前缀为前缀的路径
- 如何在自定义对象的<<运算符中添加自定义前缀
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- 以C++显示单词的所有前缀
- QXmlStreamWriter,命名空间和前缀
- 为什么 C++ 程序员更喜欢前缀 ++,而 Java 程序员更喜欢后缀 ++?
- 为什么 libclang 会错误解析带有 .h 前缀C++标头?
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
- 我需要在C++的两个字符串之间找到共同的前缀
- 更新 Visual Studio 2017,现在出现编译错误 C7510:"回调":使用依赖模板名称必须以 'template' 为前缀
- 将单个字符转换为 std::string 前缀 \x01
- 如果我有很多具有相似前缀的字符串,是否有理由从该前缀创建一个子字符串?
- 有没有办法在不使用命名空间 std 或前缀 std:: 的情况下引用 cout?
- 提升精神解析字符串以前缀开头