14

我想使用 Clang 和 LibTooling 来创建一些 C++ 源代码分析和转换工具。我已经按照教程构建了 Clang 和 LibTooling,并且我已经能够使用我构建的 Clang 二进制文件运行和创建一些分析工具并编译 C++ 程序。但是,如果我包含标准库中的头文件(在源文件或我的工具中),我会在编译或运行源文件/工具时遇到问题。例如,如果我对以下 C++ 源文件运行 clang-check:

#include <iostream>

int main() {
  std::cout << "Hello";
  return 0;
}

我收到“致命错误:找不到‘iostream’文件”。(注意:我可以编译 C++ 程序,例如带有用户定义类的程序,但不能编译使用标准库的 C++ 程序。)为了解决这个问题,我构建了 libc++(按照指南,在 llvm/project 中构建它我构建 LLVM 和 Clang 的目录),但我仍然无法获取 Clang 和使用 libc++ 的工具。现在,如果我尝试使用以下方法编译测试文件:

export CPLUS_INCLUDE_PATH="~/clang-llvm/llvm/projects/libcxx/include"
export LD_LIBRARY_PATH="~/clang-llvm/llvm/projects/libcxx/lib"
~/clang-llvm/llvm/build/bin/clang++ ~/Documents/main.cpp

然后我得到“致命错误:找不到'unistd.h'文件”。所以我的问题是:我如何正确地指出 Clang 和我的工具来使用 libc++?

我正在运行 OS X Yosemite 10.10 并使用 Clang 3.6.0。

4

4 回答 4

6

Clang 带有一些自定义包含。所以通常你在 /usr/bin/clang++ 中有 clang 并且在 /usr/lib/clang/3.6.1/include 中有包含

但 clang 将它们作为相对路径查找:../lib/clang/3.6.1/include

因此,请确保可以从 clang++ 二进制文件或您的 libtooling 应用程序访问此相对路径。

于 2015-07-09T19:20:19.523 回答
3

将您的工具包含在其中:

#include "clang/Tooling/CommonOptionsParser.h"      // For reading compiler switches from the command line
#include "clang/Tooling/Tooling.h"

static cl::OptionCategory MyToolCategory("SearchGlobalSymbols");
static cl::extrahelp MoreHelp("\nMore help text...");       // Text that will be appended to the help text. You can leave out this line.
/* Your code (definition of your custom RecursiveASTVisitor and ASTConsumer) */
/* Define class MyASTFrontendAction here, derived from ASTFrontendAction */

int main(int argc, const char **argv)
{
    /* Your code */
    CommonOptionsParser op(argc, argv, MyToolCategory);                     // Parse the command-line arguments
    ClangTool Tool(op.getCompilations(), op.getSourcePathList());           // Create a new Clang Tool instance (a LibTooling environment)
    return Tool.run(newFrontendActionFactory<MyASTFrontendAction>().get()); // Run custom Frontendaction
}

CommonOptionsParser 允许您从命令行读取传递给编译器的命令。例如,您现在可以这样调用您的工具:

your-tool yoursourcefile.c -- -nostdinc -I"path/to/your/standardlibrary"

双破折号之后的所有内容都将传递给编译器。此处描述了可能的标志:http: //clang.llvm.org/docs/CommandGuide/clang.html

-nostdinc 告诉预处理器不要寻找标准的包含路径。您可以在 -I 之后指定您自己的路径。

希望它对某人有所帮助:) 问我是否不够具体。

于 2015-11-13T11:24:33.957 回答
-1

您在构建/安装后是否移动/重命名了任何父目录?编译器应该已配置为知道在哪里查找其标准库,而无需指定环境变量路径。

于 2015-07-06T18:59:00.310 回答
-3

使用homebrew并使用命令安装 llvm

brew install llvm

你的问题应该得到解决。

于 2015-07-06T18:43:01.540 回答