2

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.

Belgorath
  • 66
  • 6
  • You did not show the command line you are using to compile. I wonder what argument you provided for clang++ `-isystem` or `-cxx-isystem` option. – Eljay Dec 15 '20 at 12:11
  • Good point. I am not compiling with clang, just using the Visual Studio integration for formatting. I added that information to the question. – Belgorath Dec 15 '20 at 12:35

2 Answers2

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.

Belgorath
  • 66
  • 6
  • FWIW, the difference between `` and `"foo.h"` is implementation-dependent. See https://stackoverflow.com/a/21594/9220132 . Generally, user code should use `"foo.h"` – jwm Feb 17 '21 at 18:20
1

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))?$'