clang-format integration

Is there any plans for a clang-format integration in cmake? cmake does provide a clean clang-tidy integration, but couldn’t find clang-format.

I don’t think so. CMake is a build tool, not a code editor…

I couldn’t find a ticket on the gitlab referring to clang-format. What type integration are you looking for?

It’s unlikely to happen. It basically requires a cycle in the build graph[1], so it’s not representible in some build tools (notably ninja).

[1] The clang-format rule “outputs” the source file, but it also needs to run whenever the source file changes. We could make it always run, but then there’s no hope for a “nothing to do” build.

Meson build system include clang-format as a target. See: Release 0.50.0

I suppose a module could be developed to do this. Something like clang_format_add_rules(TARGETS tgt1 tgt2) with a clang_format_add_target(NAME clang-format). I really don’t know about doing it by default like Meson is doing it because clang-format is terrible with compatibility across versions (e.g., if one dev has clang-format-8 and another clang-format-9, there’s likely to be lots of noise generated as each ends up running it).

1 Like

In the absence of cmake support for clang-format, is there any way to get all source files for all targets?

One can iterate over the SOURCES for each target. I would recommend explicit target enumeration, but you can iterate through the SUBDIRECTORIES directory property for the top-level directory to read BUILDSYSTEM_TARGETS for each directory instead.

@cmak , I wanted the same thing. @ben.boeckel walked through the philosophical/practical aspects of why this should not be done here.

You can configure a pre-commit hook for git to run clang-format over just the lines changed by the commit, but I don’t like doing that because that means I’m committing code I haven’t even tried to build.

What I ended up doing was changing my automated build (Bamboo) to run clang-format over the entire source tree and fail if any file was modified. This makes the enforcement of formatting a CI step as Ben suggested; your build fails very quickly if you didn’t do the formatting like you should.