'clang-format main include sorting with folders prefix

I am trying to get clang-format to recognize the main include for foo.cpp in the following setup:

project/my_lib
├── CMakeLists.txt
├── include
│   └── project
│       └── my_lib
│           └── foo.hpp
├── src
│   └── foo.cpp
└── tests
    └── foo_test.cpp

And foo.cpp has the following content:

#include <project/another_lib/bar.hpp>
#include <project/my_lib/foo.hpp>
#include <vector>

// ...

The problem I think I have identified is the following: clang tries to identify the 'main' include based on the file name, in this case foo.cpp. And when it looks at #include <project/my_lib/foo.hpp> it doesn't recognize this as the 'main' include for this cpp file. I know it is possible to specify suffixes for the "main include file" logic, but what would be needed here is a prefix regex.

Any help as to how I could get clang to set the right include to priority 0 in the example above?

Reference: Clang format options, section "IncludeCategories" and following

Edit: I am using clang-format as integrated in Visual Studio 2019, which means I do not think I have access to the command line options. Moreover, this being a shared project, I'd like to work off of the default behavior.



Solution 1:[1]

Just as a quick update, which kind of solved my issue: if the include uses regular quotes (") then clang-format bundled with Visual Studio seems to pick up the "main" header and order it accordingly.

Not ideal, but still a working solution.

Solution 2:[2]

Even though you are using Visual Studio, you can still have a .clang-format file on the top level of the repository and Visual studio will be able to detect and apply the formatting as per the rules set in the file.

To fix the issue you mentioned, use the following options. You can ignore the "stdafx.h" if your code base does not use that.

# Sort includes, import and using declarations.
SortIncludes: true
SortUsingDeclarations: true

IncludeBlocks: Regroup

IncludeIsMainSourceRegex: '$?'

# Group includes, sorting lowest priority number first
IncludeCategories:
  - Regex:           '[<"]stdafx.h'
    Priority:        -1
  - Regex:           '[<"].*(/|\\).*'
    Priority:        2
  - Regex:           '^<.*'
    Priority:        1    
  - Regex:           '.*'
    Priority:        3


IncludeIsMainRegex: '([-_](test|unittest))?$'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Belgorath
Solution 2 Trilokesh Pradhan