cdocumentationdoxygenclang-format

Best practice for code snippet in doc comment for C project?


I'm familiar with Rust, and recently I'm going to write a C project. In Rust, we usually embed some code snippets as usage examples directly in the doc comment. However, I found this hard to be combined with doxygen and clang-format.

Specifically, I found clang-format will format the code snippet in doc comment as if it is normal english sentences, such as

/**
 * @code
 * char *a_very_very_very_long = "which makes it need to enter another line to fix";
 * if (foo > 1) {
 *     return;
 * }
 * @endcode
 */
int foo = 0;

will be formatted to

/**
 * @code
 * char *a_very_very_very_long = "which makes it need to enter another line to
 * fix"; if (foo > 1) { return;
 * }
 * @endcode
 */
int foo = 0;

I filed an issue to the LLVM project, and they said that clang-format is not intended to format code in docs.

I don't think this is an rare case in C development, and since both doxygen and clang-format has been widely used for a long time, I wonder what is the best practice to doing so? (Even if the code may not be properly formatted as code, it should not be wrongly formatted to break its original pattern)

P.S. I know I could turn off clang-format to skip the whole comment, but I do want clang-format to format other normal sections in the doc comment.


Solution

  • The easiest and most common solution is temporarily disabling clang-format around sensitive regions:

    /**
     *
     * @code
     * // clang-format off
     * char *a_very_very_very_long = "which makes it need to enter another line to fix";
     * if (foo > 1) {
     *     return;
     * }
     * // clang-format on
     * @endcode
     */
    int foo = 0;
    

    This explicitly instructs the clang-format to avoid reformatting just this code snippet, while still properly formatting the rest of your comments.

    You can also use markdown-style code fences, which Doxygen supports:

    /**
     * Usage example:
     *
     * ~~~{.c}
     * // clang-format off
     * char *a_very_very_very_long = "which makes it need to enter another line to fix";
     * if (foo > 1) {
     *     return;
     * }
     * // clang-format on
     * ~~~
     */
    int foo = 0;