Clang CFE编译无法读取文件



我正在尝试使用Clang Compiler FrontEnd编译测试文件,代码如下:

#include <string>
#include <vector>
#include <memory>
#include <iostream>
#include <llvm/Support/Host.h>
#include <llvm/Support/Program.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/VirtualFileSystem.h>
#include "clang/Basic/LLVM.h"
// #include <clang/Driver/ToolChain.h>
#include <clang/Driver/Driver.h>
#include <clang/Basic/Diagnostic.h>
#include <clang/Basic/DiagnosticIDs.h>
#include <clang/Basic/DiagnosticOptions.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Driver/Compilation.h>
using namespace clang::driver;
using namespace clang;
std::string pwd = "/home/arch/Documents/CFE/Examples/Compile/";
std::string target_executable = pwd + "target";
int main()
{
llvm::IntrusiveRefCntPtr<DiagnosticsEngine> DE(clang::CompilerInstance::createDiagnostics(new DiagnosticOptions));
llvm::ErrorOr<std::string> clangPath = llvm::sys::findProgramByName("clang++");
Driver D(StringRef(clangPath.get().c_str()), llvm::sys::getDefaultTargetTriple(), *DE, "clang LLVM compiler", InMemoryFileSystem);
// D.setCheckInputsExist(false);
std::vector<const char *> args;
args.push_back(clangPath.get().c_str());
args.push_back((target_executable + ".cpp").c_str());
args.push_back("-cl-std=clc++2021");
args.push_back(("-o " + target_executable + ".spv").c_str());
ArrayRef<const char *> compileArgs(args);
std::unique_ptr<Compilation> C(D.BuildCompilation(compileArgs));
assert(C > 0);
bool CallbackHasCalled = false;
C->setPostCallback(
[&](const Command &Cmd, int Ret)
{ std::cout << "postCallback return value: " << Ret << std::endl; 
CallbackHasCalled = true; });
const JobList &Jobs = C->getJobs();
auto &CmdCompile = Jobs.getJobs().front();
const Command *FailingCmd = nullptr;
assert(C->ExecuteCommand(*CmdCompile, FailingCmd));
assert(FailingCmd);
}

使用下面的CMakeLists.txt:

cmake_minimum_required(VERSION 3.23)
project("CLANG_CFE")
find_package(Clang REQUIRED)
target_precompile_headers(clangBasic PUBLIC)
execute_process(COMMAND clang-config --libs OUTPUT_VARIABLE LLVM_LIBRARIES)
execute_process(COMMAND clang-config --cxx-flags OUTPUT_VARIABLE LLVM_CXX_FLAGS)
add_executable(compile_example main.cpp)
target_compile_options(compile_example PRIVATE ${LLVM_CXX_FLAGS})
set(CLANG_LIBS clangBasic clangDriver clangFrontend)
target_link_libraries(compile_example PRIVATE  ${CLANG_LIBS} LLVMSupport)

代码可以正常编译,但无法读取target_executable,导致以下错误:

error: no such file or directory: 'P�ZUU'

是读写权限错误吗?

这是一个使用绝对路径的问题,方法Driver::DiagnoseInputExistence自动拒绝以"/"开头的文件路径。

使用相对文件路径解决了这个问题。

最新更新