Sunday, April 17, 2011

C/C++ include file resolution


Another why-oh-why experience today. I'm trying to find out how the preprocessor is resolving include files, like: what paths will be searched first.

I expected the following behaviour:
  • #include <somefile.h> : only search the paths that were passed to the compiler using the -I switch
  • #include "somefile.h" : first search the folder in which the file being examined lives, only then start searching the folders passed to the compiler using -I.
Instead I found that the behaviour is compiler dependendent (hence the why-oh-why?!) According to this article:
  • the #include <somefile.h> variant:

    StepVisual studio GCC
    1 paths passed by /I paths passed by -I
    2 paths specified in INCLUDE environment variable system directories
  • the #include "somefile.h" variant

    StepVisual studio GCC
    1 the same directory as the file that contains the #include statement the same directory as the file that contains the #include statement
    2 the directories of any previously opened include files in the reverse order in which they were opened directories passed in by the -iquote option
    3 paths passed by /I inside the quote directories
    4 paths in the INCLUDE environment variable
To clarify the "inside the quotes" method: for example if /usr/include/sys/stat.h contains #include "types.h", GCC looks for types.h first in /usr/include/sys, then in its usual search path. So what now? Do we really need separate project resolution algorithms that mimick these approaches? Since I'm not trying to keep the tool's command line options compatible with those of the compiler, I think I can get away with a simpler scheme (counter examples are welcome of course). For now include files will be resolved as follows:
  • Step 1: check the folder of the file being examined (only if the "" style of include was used)
  • Step 2: check the include folders that were passed to the tool using -I like options (in the order in which they were passed in)

No comments:

Post a Comment