[clang-format] Need help to make auto-formatted C macros readable

I got stumbled on making clang-format work in one pre-commit CI and need suggestions to take actions. Thanks in advance!

This is the clang-format diff from the pre-commit CI of a pull request. The automatic formatted lines ( line 210 to line 267, line 284 to line 404, code between 780 to 970, etc) are indented in a way that’s hard to read at least for me.

Using // clang-format off and // clang-format on selectively around code regions (as demonstrated in a draft pr is one option. But it goes in the opposite of the good direction to enable clang-formats everywhere.

Ideally .clang-format could be configured such that the formatting works automatically going forward. But what options do I need to make the formatted result more readable?

Clang-format version 18 introduced formatting option SkipMacroDefinitionBody. Does this option apply on both macro definitions and macro usages?

Also pre-commit CI uses clang-format version 17.0.1 [1] currently. In order to add a new option to LLVM upstream, shall I wait after the pre-commit CI upgrades its clang-format version?

[1] From the log in the link

Install Clang-format
Run aminya/setup-cpp@v1
Installing clangformat 17.0.1
took 19 seconds
✅ clangformat was installed successfully:
- The installation directory is /usr/lib/llvm-17
- The binary directory is /usr/lib/llvm-17/bin
setup-cpp finished

Tagging @pogo59 just in case you have suggestions to clang-format two files (1 and 2), which may fit in the good direction to clang-format all the things as proposed in RFC: clang-format all the things!.

That looks like a clang-format bug; I’m guessing it gets confused about the appropriate indentation, likely because the macro invocations look kind of like function prototypes that are not terminated by a semicolon. I recommend filing an issue against clang-format. I am not a clang-format maintainer so I can’t say anything more useful about it.

In the short term, adding clang-format directives is probably the way to go. I’d add comments explaining why the directives are there, so in the future someone can figure out whether it is okay to remove them.

1 Like

thanks for the response! I filed a Github issue to track this, and will link it as a reason (i.e., // clang-format off:<reason>) when sending out the pr.

In the meantime, some things to try as a workaround:

  • Put a blank line between macro invocations
  • Terminate macro invocations with a semi-colon
  • Put a // comment after the macro invocation