Using libclang 6.0.1: stddef.h not found

Viewed 1484

To get started with libclang, I build a very simple program that tries to load a very simple source file. It fails with 'stddef.h' file not found.

Here is the program using libclang:

#include <clang-c/Index.h>
int main() {
    CXIndex index = clang_createIndex(1,1);
    const char *source_path = "foo.cpp";
    clang_createTranslationUnitFromSourceFile(index,"foo.cpp",0,0,0,0);
}

(For conciseness, I left out code that is irrelevant to reproducing the issue).

And here is the file I am trying to load, foo.cpp:

#include <stddef.h>
int main() {}

I am using LLVM and Clang 6.0.1, compiled from source as follows:

cmake .. -DCMAKE_INSTALL_PREFIX=$HOME/local -DCMAKE_PREFIX_PATH=$HOME/local -DCMAKE_BUILD_TYPE=Release
make
make install

A quick search yields this promising post: Clang Error - stddef file not found? Unfortunately, this is about llvm 3.5, and I am using llvm 6.0.1. Also, the directory $HOME/local where I installed LLVM and Clang does not have a /usr/lib directory, so the solution proposed there does not work here.

The stddef.h header is present at $HOME/lib/clang/6.0.1/include/stddef.h. Explicitly adding this path as a -isystem option to the clang_createTranslationUnitFromSourceFile call solves the problem.

Moreover, the include search path used by clang_createTranslationUnitFromSourceFile is not the same as that used by clang++; clang++ foo.cpp works without errors.

Is there any documentation on the include search path used by clang_createTranslationUnitFromSourceFile and similar functions in libclang, so that I can determine which include paths need to be added?

Any other suggestions on how to invoke clang_createTranslationUnitFromSourceFile with a correct include search path, equivalent to the path used by clang++?

1 Answers

libclang works as if you tried to compile the file, i.e.: to parse a file it needs to know where to look for the headers, and potentially other info such as macro definitions, compile flags, etc.

clang_createTranslationUnitFromSourceFile has two parameters: num_clang_command_line_args and clang_command_line_args. There you need to pass actual header search path, e.g.:

const char *cli_args[] = { "-I", "~/local" };
clang_createTranslationUnitFromSourceFile(index, "foo.cpp", 2, cli_args, 0, 0);
Related