[cfe-dev] How to determine clang's system include dirs, to set in ASTVisitor?

Sean Silva silvas at purdue.edu
Wed Dec 19 17:43:24 PST 2012


This is probably the #1 issue that people run into when using the
clang libraries.

I forget exactly which are the magic functions that will get things to
"kind of" work. I think you can use something like
`clang::createInvocationFromCommandLine` which will set up "most"
things for you (it calls into `CompilerInvocation::CreateFromArgs`
which might be all you need).

Ultimately, you will run into a big problem, which is that some
critical headers that are needed for basically everything (e.g.
<stddef.h>) are currently found in a really nasty way which relies on
finding the headers in a specific directory *relative to the
executable*, which means that unless your executable is embedded in a
particular directory structure it will fail to find these (for the
details, see `CompilerInvocation::GetResourcesPath` and its
callsites).

This special directory is usually passed by clang to `clang -cc1`
through its `-resource-dir` command line argument. If you feel like
hardcoding this, you can look at the argument to `-resource-dir` with

clang++ '-###' -c foo.c 2>&1 | tr ' ' '\n' | grep -A1 resource

(the file foo.c must actually exist, but need not contain anything
meaningful). Alternatively, you can copy the special headers into
their special directory structure relative to your executable (this
might be the easiest thing to do). In the clang source distribution,
you can find the headers in lib/Headers/, and otherwise you can grab
them from the resource dir printed by the above command. Note that if
you build your program as an executable within the llvm/clang build
system, the built executable will be put inside the "special"
directory structure (however, having to drag around (and build!) all
of llvm/clang along with your tool is probably more annoying than the
other two options I mentioned.

Yes, having to hardcode this this is a pain in the ***. Unfortunately,
it is a pretty nasty problem to solve. Probably the most palatable
option currently is to embed the headers inside the clang libraries
(in the binaries) and have it fall back on those if the current
"hardcoded" lookup fails. But that requires messing around with the
build system; nobody has stepped up to do that.

-- Sean Silva



More information about the cfe-dev mailing list