Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equal header file in different include paths

Say we have two header files:/directory1/A.hpp and directory2/A.hpp. The contents of those two headers are different!

Our build target A.cpp needs directory1 and directory2 as include paths, since there are other needed header files in both directories.

Now, in A.cpp there is a #include "A.hpp" statement.

Which version of A.hpp will the preprocessor choose?

Isn't it likely that if one works with a 3rd party software, that so such a situation might occur?

like image 261
Juergen Avatar asked May 30 '13 09:05

Juergen


4 Answers

What happens in this case depends on the compiler in question (consult the docs of the compiler you use).

Situations like these are the reason why using "unqualified" header names is generally a bad idea. Always structure your include directories to leave a part of the path a necessary component of the name. E.g.

#include <boost/preprocessor.hpp>
#include <gl/GL.h>

instead of

#include <preprocessor.hpp>
#include <GL.h>
like image 86
Angew is no longer proud of SO Avatar answered Nov 20 '22 01:11

Angew is no longer proud of SO


The include directive with double quotes pastes the file referenced in its literal form. The file path is considered to be relative to the source file location.

So if you had #include "directory1/A.hpp", it will include the obvious one. If you #include <A.hpp> or #include "A.hpp", it depends which appears first in your search path.

Generally, you should have specific and descriptive names to prevent contention here. Using directories the same way you'd use a C++ namespace is a decent enough practice. Look at the structure of libraries like libxml++ and gtkmm.

like image 5
Taywee Avatar answered Nov 20 '22 03:11

Taywee


It will depend of your compilation options, and more specially of your include path.

If directory1 is in the include path, it will be the /directory1/A.hpp, else if the directory2 is in the include path, it will be the /directory2/A.hpp. If directory1 and directory2 are both in the include path, the compiler will ask you to specify the directory, like #include "directory1/A.hpp".

like image 3
nouney Avatar answered Nov 20 '22 03:11

nouney


The compiler picks include files in the order that the include directories are listed as arguments to -I. The first file that is found is used.

In a case where there are two files with the same name, you should specify which one you want in the source file.

like image 1
Mats Petersson Avatar answered Nov 20 '22 02:11

Mats Petersson