c++cformatcode-formattingclang-format

clang-format option to set penalty for breaking preprocessor directives


Is there an option to set the penalty for breaking preprocessor directives into multiple lines?

For example, if I have the following snippet:

#define my_constant 1 // Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut 

And this .clang-format:

BasedOnStyle: Google
ColumnLimit: 80

The file gets formatted to this:

#define my_constant \
  1  // Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
     // tempor incididunt ut labore et dolore magna aliqua. Ut

However, I want it to format similar to this:

#define my_constant 1   // Lorem ipsum dolor sit amet, consectetur adipiscing 
                        // elit, sed do eiusmod tempor incididunt ut labore et 
                        // dolore magna aliqua. Ut 

I've tried the existing penalty options here, but I haven't been able to find one that works.

Any advice would be appreciated.


Solution

  • As far as I know, that is not possible. Yet. But you could do one of the following:

    A) Suppress formatting for that region altogether by adding the following two comments:

    // clang-format off
    #define my_constant 1   // Lorem ipsum dolor sit amet, consectetur adipiscing 
                            // elit, sed do eiusmod tempor incididunt ut labore et 
                            // dolore magna aliqua. Ut 
    // clang-format on
    

    I understand, that this will be laborious if you run into that situation often.

    B) Add the long comment before the preprocessor directives. If you use Doxygen, there will be different ways to do so. I won't go into detail, but have a look here if that sounds good for you.

    /** Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
     * tempor incididunt ut labore et dolore magna aliqua. Ut
     */
    #define my_constant 1
    

    Of course, you could keep the // comment style, but that is supposed to be used for single line comments.

    C) Try to minimize the use of preprocessor directives. There are different approaches to achieve that depending on the situation. Maybe this is a tiny starting point.