Python clang不搜索系统包含路径
在使用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自动使用这些路径就太好了。
1 个回答
5
这个问题已经存在一段时间了,所以我来尝试自己回答一下。
看起来连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。