我正在使用 Clang C++ API。由于 API 没有正确使用智能指针,我一直在为所有权而苦苦挣扎。到目前为止,我自己发现了所有问题,但这个问题让我很烦恼。当代码执行时,我遇到了访问冲突。我相当肯定这是一个双重删除,但由于文档不存在,我不知道去哪里看。幸运的是,复制程序相当短。有什么建议么?
#define _SCL_SECURE_NO_WARNINGS
#pragma warning(push, 0)
#include <clang/CodeGen/CodeGenAction.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Sema/Lookup.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/Mangle.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Sema/Sema.h>
#include <clang/Sema/SemaConsumer.h>
#include <clang/Sema/CodeCompleteConsumer.h>
#include <llvm/LLVMContext.h>
#include <llvm/Support/DataTypes.h>
#include <llvm/Module.h>
#include <llvm/Support/Host.h>
#pragma warning(pop)
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
llvm::LLVMContext c;
llvm::Module m("", c);
clang::EmitLLVMOnlyAction emit(&c);
emit.setLinkModule(&m);
clang::CompilerInstance CI;
std::string errors;
llvm::raw_string_ostream error_stream(errors);
clang::DiagnosticOptions diagopts;
clang::TextDiagnosticPrinter printer(error_stream, &diagopts);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagids(new clang::DiagnosticIDs);
clang::DiagnosticsEngine engine(diagids, &diagopts, &printer, false);
CI.setDiagnostics(&engine);
CI.createFileManager();
CI.createSourceManager(CI.getFileManager());
llvm::raw_null_ostream empty;
clang::PrintingCodeCompleteConsumer print(CodeCompleteOptions(), empty);
clang::TargetOptions target;
target.Triple = llvm::sys::getDefaultTargetTriple();
CI.setTarget(clang::TargetInfo::CreateTargetInfo(engine, &target));
CI.createPreprocessor();
CI.createASTContext();
clang::SemaConsumer* cons = new clang::SemaConsumer();
CI.setASTConsumer(cons);
CI.createSema(clang::TranslationUnitKind::TU_Complete, &print);
cons->InitializeSema(CI.getSema());
clang::FrontendInputFile f("header", clang::InputKind::IK_CXX, true);
emit.BeginSourceFile(CI, f);
emit.Execute();
emit.EndSourceFile();
emit.takeModule();
clang::LookupResult lr(CI.getSema(), clang::DeclarationName(CI.getPreprocessor().getIdentifierInfo("function")), clang::SourceLocation(), clang::Sema::LookupNameKind::LookupOrdinaryName);
auto result = CI.getSema().LookupName(lr, CI.getSema().TUScope);
std::string temp;
llvm::raw_string_ostream out(temp);
CI.getASTContext().createMangleContext()->mangleName(lr.getFoundDecl(), out);
auto fun = m.getFunction(temp);
std::cout << fun->getName().str();
return 0;
}
编辑:另外,我是否提到过,如果我更改它以使文件实际存在,即使它是一个微不足道的程序,Clang 在执行操作时也会因访问冲突而失败,甚至在EndSourceFile
. 为什么。