October 22, 2024
Chicago 12, Melborne City, USA
C++

C and C++ compiler include order and relative paths


I did a test with the following folder structure:

MainFolder
    main.cpp
    LibraryFile.h
    Files
        LibraryFile.h
    Library1Name
        MainHeader.h        
        LibraryFile.h
        Files
            LibraryFile.h
    Library2Name
        MainHeader.h
        LibraryFile.h
        Files
            LibraryFile.h

Let’s assume the MainFolder (root) folder is in the include paths and nothing else. Now in main.cpp I do:

#include "Library1Name/MainHeader.h"

Both MainHeader.h from Library1 and Library2 include:

#include "LibraryFile.h"
#include "Files/LibraryFile.h"

The point here is to create EXACTLY the same folder structure and names between all three versions:

The Library1 version
The Library2 version
The Root Folder version

As far as I can see now there is a potential conflict between referring to those files within Library1, or, seeing as the main root folder is in the include paths, referring to the root version.

Question 1: Is the order here defined?

On my system it picks the one inside Library1. So there was no conflict. However, let’s just say there IS a conflict, as I believe I had one earlier, what would be the effect of adding "./" as the include path? For example in main.cpp:

#include "Library1Name/MainHeader.h"

And then in Library1 MainHeader:

#include "./LibraryFile.h"
#include "./Files/LibraryFile.h"

From my test, when it did conflict (though I can’t reproduce the conflict anymore), adding "./" solved the conflict. My theory is that if you do this the compiler can’t pick the root folder version, because you’ve specified "./" which specifically means relative to the very file in which you’ve written it. For clarification, "./" doesn’t mean the folder path AFTER being included in a CPP file, which would mean "THE LOCATION OF THE CPP FILE". Rather it’s ALWAYS referring to "THE LOCATION OF THE FILE IN WHICH "./" WAS WRITTEN. Which is the header file.

Question 2: Does "./" always do this?

Further, consider that we add path "MainFolder/Library2Name" to the include path. This would mean we introduce ANOTHER conflict, but, as I said earlier, specifying "./" eliminates all conflicts.

To what extent am I right?

Also, there are differences between #include "" and #include <>, but as this is really complicated let’s forget <> and focus on "". The test I did is here.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video