Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indenting preprocessor directives with clang-format

I am working on a c++ project where I am using a lot of #pragma omp. I use the wonderful clang-format for tidiness but it always deletes the indentation for all preprocessor directives. Is there a way to change that behavior? Or is there another formatting tool that is more recommendable? Or should I avoid using these tools at all?

like image 263
dawirstejeck Avatar asked Jun 29 '14 12:06

dawirstejeck


People also ask

Should preprocessor directives be indented?

C static code analysis: Preprocessor directives should not be indented.

How do you customize your clang-format?

clang-format supports two ways to provide custom style options: directly specify style configuration in the -style= command line option or use -style=file and put style configuration in the . clang-format or _clang-format file in the project directory.

Does clang-format work for C?

clang-format is located in clang/tools/clang-format and can be used to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.

How do I apply a clang file format?

You can install clang-format and git-clang-format via npm install -g clang-format . To automatically format a file according to Electron C++ code style, run clang-format -i path/to/electron/file.cc . It should work on macOS/Linux/Windows.


2 Answers

As of version 6.0, the option IndentPPDirectives can be used. Usage is described in this review.

Using IndentPPDirectives: None results in:

#if FOO #if BAR #include <foo> #endif #endif 

While IndentPPDirectives: AfterHash gives:

#if FOO #  if BAR #    include <foo> #  endif #endif 

Edit: see @Gabriel Staples' answer for details on the BeforeHash option introduced in clang-format version 9.

like image 156
merlinND Avatar answered Oct 08 '22 09:10

merlinND


You might want to just patch it yourself and make a pull request.

It's not that hard, I made a similarly mundane pull request once. The clang-format code is pretty tidy. Clang-format already handles code comments in the way that you want, aligning them to the surrounding code (at least it has an option to enable this) so making a patch to treat certain PP directives the same way should be straightforward.

Alternatively, you can just write the patch yourself and compile clang yourself from source with the extra option, for use in your project. I also did this before I decided to send them the patch.

It seriously took me only a few hours to figure out how to do this, their code is much cleaner than the code of many other open source projects.

like image 28
Chris Beck Avatar answered Oct 08 '22 08:10

Chris Beck