lorakis
lorakis

Reputation: 23

How to keep clang-format include header at the top of the file?

I'm running into an issue with clang-format setup in my project.

As all my includes are in angled brackets <> I've got and issue with IncludeIsMainRegex.

I want to keep something like this:

For every MyFile.cpp:

#include <directory/MyFile.hpp>

#include <string>
#include <utility>

#include <directory/SecondFile.hpp>
#include <directory/ThirdFile.hpp>

But no matter what I do in IncludeIsMainRegex, it is always sorted like this when using IncludeBlocks: Regroup

#include <string>
#include <utility>

#include <directory/MyFile.hpp>
#include <directory/SecondFile.hpp>
#include <directory/ThirdFile.hpp>

I tried with setting IncludeIsMainRegex: '<.*$1>', but it doesn't work. It has to be something universal, that will dynamically assume file name in every file and based on that will set it at the top of the include list. Is it even possible?

Upvotes: 0

Views: 123

Answers (1)

Eran
Eran

Reputation: 2400

Usually, it is a nice to have the includes ordered. clang-format can also sort them in groups (separate system includes from workspace includes and even from the current file's corresponding header (e.g. for Foo.cpp , Foo.hpp will be placed at the top in a group of its own).

However, in some cases, sorting the includes has some unwanted affects. For this you could have:

#include <b.h>
#include <a.h>

// clang-format off
// .. content here will be untouched by clang-format
// clang-format on
  • clang-format allows to override the include sorting from the command line by passing: clang-format --sort-includes ...

HTH,

Eran

Upvotes: 0

Related Questions