将 .pch 文件与 libclang API 一起使用

using .pch files with libclang api's

本文关键字:一起 API libclang pch 文件      更新时间:2023-10-16

我试图使用.pch,如下面的例子中所示http://clang.llvm.org/doxygen/group__CINDEX.html,但它似乎不工作。

char *args[] = {"-Xclang", "-include-pch=IndexTest. "pch "};

TU = clang_createTranslationUnitFromSourceFile(Idx, "IndexTest.c", 2, args, 0,0);

libclang读取-include-pch标志失败,它将其读取为-include标志。

我想要的是:我的代码依赖于很多头文件。我想解析并创建翻译单元一次,并将其保存为pch文件。现在我只想解析一个文件。有可能做到吗?

我遇到过类似的问题,也许解决方案也类似:

我正在使用clang在内部编译一些代码,并将包含参数的矢量发送给编译器:

llvm::SmallVector<const char *, 128> Args;
Args.push_back("some");
Args.push_back("flags");
Args.push_back("and");
Args.push_back("options");
//...

添加像"Args。Push_back ("-include-pch myfile.h.pch");"将导致错误,因为-include-pch标志被读取为-include标志。

在这种情况下,如果你想使用pch文件,你必须使用"two"参数:

llvm::SmallVector<const char *, 128> Args;
//...
Args.push_back("-include-pch");
Args.push_back("myfile.h.pch");
//...

像这样使用:

char *args[] = { "-Xclang", "-include-pch", "IndexTest.pch" };

这将解决你的问题。然而,有一个更大的问题,当你想使用多个pchs…它不能工作,即使使用clang++编译器。

在clang的文档中,您可以找到源代码示例:

// excludeDeclsFromPCH = 1, displayDiagnostics=1
Idx = clang_createIndex(1, 1);
// IndexTest.pch was produced with the following command:
// "clang -x c IndexTest.h -emit-ast -o IndexTest.pch"
TU = clang_createTranslationUnit(Idx, "IndexTest.pch");
// This will load all the symbols from 'IndexTest.pch'
clang_visitChildren(clang_getTranslationUnitCursor(TU), TranslationUnitVisitor, 0);
clang_disposeTranslationUnit(TU);
// This will load all the symbols from 'IndexTest.c', excluding symbols
// from 'IndexTest.pch'.
char *args[] = { "-Xclang", "-include-pch=IndexTest.pch" };
TU = clang_createTranslationUnitFromSourceFile(Idx, "IndexTest.c", 2, args, 0, 0);
clang_visitChildren(clang_getTranslationUnitCursor(TU), TranslationUnitVisitor, 0);
clang_disposeTranslationUnit(TU);

虽然我没有检查它。你找到有效的解决方案了吗?查看我关于PCH的问题