Adler Amorette
Adler Amorette

Reputation: 11

Include directive can match two files: what's the priority?

Which file is preferred when there are two files with the same specified name: the first is in the directory in which the file which includes it lies, and the second is somewhere else but its directory is in include path?

E.g.: (where proj_dir is in include path)

.
└── proj_dir
    ├── a
    │   ├── a.c -> #include "b.h"
    │   └── b.h
    └── b.h

Does anything change when a is also in the include path?

Upvotes: 0

Views: 694

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

When including files using double-quotes " then the preprocessor will look first in the same directory as the file doing the including.

In your case, if the file proj_dir/a/a.c have:

#include "b.h"

then it will include the proj_dir/a/b.h file.

If no file is found in the same directory, then the preprocessor will look through the include paths.


If including using angle brackets <> then the preprocessor will look first in the include paths.

Also note that the preprocessor will look in each include path in the order specified, and stop looking at first hit. So if you have an include file that is in multiple include paths, only the first one found will be included. So the order in which you add paths to search matter.


While this behavior is really implementation defined (as mentioned in a comment), the general behavior from the major implementations doesn't deviate very much from this.

The only deviation is really how system include paths are added. MSVC (for example) have multiple options to add include paths, and they are search in a specific order. While GCC have a preconfigured list of system directories that are searched first.

But as for the behavior of double-quoted inclusion, all implementations uses the directory of the current file first.

Upvotes: 2

Related Questions