2014-10-18 126 views
4

当从Python使用libclang时,似乎不会自动搜索系统的包含路径。Python铛不搜索系统包含路径

有没有可靠的方法来获得这些路径?我不喜欢硬编码路径,因为我正在编写可在各种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自动使用它,那将是非常好的。

+1

[this](http://stackoverflow.com/a/22536040/528929)答案没有比libclang更好的方法了(似乎libtooling更强大);一个解决方法是向'clang -E -x C++/dev/null -v'添加一个调用,并在python脚本中过滤结果。 – 2014-10-19 04:12:28

+1

考虑使用'-isystem '而不是'-I '来通知libclang的系统包含路径 – 2014-10-30 23:02:16

回答

2

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

看来,即使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.cppCrossWindowsToolChain.cppMinGWToolChain.cpp

我所希望的是InitHeaderSearch.cpp中的代码将通过libclang暴露给Python。