Search code examples
c++clang-format

Can clang-format eliminate whitespace within angle bracket of include statement?


Consider this include statement. Notice the extra space after iostream:

#include <iostream >

msvc will compile this, but gcc does not. So our Windows devs may not see this failure until our CI process builds with gcc.

Is there a way to get clang-format to remove the extra space within the angle brackets of the include statement?

I've looked through the documentation for things related to includes and spaces, but cannot find anything that removes the space.

SpacesInAngles - This controls spaces in angle brackets for things like templates, but does not change includes. (We prefer spaces in angles in most of our code).


Solution

  • You definitely can't do this with a compiler-agnostic formatting tool because the exact content within angle brackets can matter. The standard says that what exact file is searched for based on the exact string within angle brackets is implementation-defined, and when you look at e.g. GCC preprocessor documentation (section 2.6), you find that even the spaces are used.

    On Linux, I can touch "myheader.h " and compile the following with G++ 14 and -I $(pwd):

    #include <myheader.h >
    
    int main() {}
    

    Note the trailing spaces in filename (yes, this is possible!) and include directive. Removing either leads to compilation error.

    What to do?

    I'm assuming here that you want to detect and remove these spaces in all cases, not just when it would lead to a compilation error later. Otherwise you can just take the lazy way, ignore it and deal with compilation errors if they appear - it's not particularly difficult to fix and devs will learn to avoid it if it's a common enough mistake to warrant this attention.

    Make a custom pre-commit hook (or CI job etc) where you look for this pattern. A simple pair of extended regexes like ^#include <\s+(.*)>$ and ^#include <(.*)\s+>$ should cover 99% of cases - including block comments and ifdefs. Then you can raise a warning or error with suggested fix.

    Of course, this will make your codebase unable to include anything with leading or trailing spaces, which is why code formatters don't offer this option.