【问题标题】:Python clang does not search system include pathsPython clang 不搜索系统包含路径
【发布时间】:2014-12-13 23:24:14
【问题描述】:

在 Python 中使用 libclang 时,它似乎不会自动搜索系统的包含路径。

有没有可靠的方法来获取这些路径?我不喜欢硬编码路径,因为我正在编写将在各种 UNIX 系统上运行的代码。

例如,给定 test.cpp

#include <stdio.h>

int main()
{
  puts("Hello, world!");
}

和 test.py

from clang.cindex import Index

tu = Index.create().parse(None, ["test.cpp"])
print(list(tu.diagnostics))

运行python test.py 将打印:

[<Diagnostic severity 4, location <SourceLocation file 'test.cpp', line 1, 
 column 10>, spelling "'stdio.h' file not found">]

当然,我可以通过这样做找到系统包含路径

$ clang -v -E test.cpp

并将"-Isome/path" 添加到parse 参数列表中,即

args = ["-I/Applications/[...]", "test.cpp"]

这确实有效并且不会产生错误。

但是,这不是可移植的,如果我能以编程方式让 clang 自动使用它们,那就太好了。

【问题讨论】:

  • this 回答只有使用 libclang 没有更好的方法(似乎 libtooling 更有能力);一种解决方法是添加对clang -E -x c++ /dev/null -v 的调用并在python 脚本中过滤结果。
  • 考虑使用-isystem&lt;path&gt;而不是-I&lt;path&gt;来通知libclang系统包含路径

标签: python c++ clang libclang


【解决方案1】:

这个问题已经有一段时间了,所以我会尝试自己回答。

似乎即使是 Clang 本身也主要使用硬编码的路径。

它枚举候选路径并添加适合当前上下文的路径。这可以在clang/lib/Frontend/InitHeaderSearch.cpp 中看到。例如,

AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
                           "i686-apple-darwin10", "", "x86_64", triple);
AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.0.0",
                           "i686-apple-darwin8", "", "", triple);

// ...

对于Linux,这段代码有注意事项:

llvm_unreachable("Include management is handled in the driver.");

在clang/lib/Driver/ 下,我们可以在ToolChains.cpp、CrossWindowsToolChain.cpp 和MinGWToolChain.cpp 等文件中找到更多此类路径。

我希望InitHeaderSearch.cpp 中的代码可以通过 libclang 暴露给 Python。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2011-02-19
    • 2015-03-14
    • 1970-01-01
    • 2013-07-14
    • 2011-04-26
    • 1970-01-01
    相关资源
    最近更新 更多