C/C++ – Finding Header Files

cheaders

A C or C++ compiler looks for header files using a strict set of rules: relative to the directory of the including file (if "" was used), then along the specified and default include paths, fail if still not found.

An ancillary tool such as a code analyzer (which I'm currently working on) has different requirements: it may for a number of reasons not have the benefit of the setup performed by a complex build process, and have to make the best of what it is given. In other words, it may find a header file not present in the include paths it knows, and have to take its best shot at finding the file itself.

I'm currently thinking of using the following algorithm:

  1. Start in the directory of the including file.

  2. Is the header file found in the current directory or any subdirectory thereof? If so, done.

  3. If we are at the root directory, the file doesn't seem to be present on this machine, so skip it. Otherwise move to the parent of the current directory and go to step 2.

Is this the best algorithm to use? In particular, does anyone know of any case where a different algorithm would work better?

Best Answer

I'm currently thinking of using the following algorithm:

  1. Start in the directory of the including file.

  2. Is the header file found in the current directory or any subdirectory thereof? If so, done.

  3. If we are at the root directory, the file doesn't seem to be present on this machine, so skip it. Otherwise move to the parent of the current directory and go to step 2.

Is this the best algorithm to use? In particular, does anyone know of any case where a different algorithm would work better?

I have been working in projects that had a setup like this:

prj  
   |  
   +-config.h  
   |  
   +-sub_A  
   | |  
   | +-config.h  
   | +-...  
   |  
   +-sub_B
   | |  
   | +-config.h  
   | +-...  
   |  
   +-...

Those are then referred to as

#include "config.h"
#include "sub_A/config.h"
#include "sub_B/config.h"
...

Simply searching for a header with a matching file name would blow this, which I believe means that a different algorithm would work better.