Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Configuring Clang-Format for K&R C/C++ Style

Tech Apr 18 11
#include "custom_driver.h"
#include "system_bus.h"

#include <algorithm>
#include <deque>
#include <list>
#include <memory> //! Header grouping + sorting
#include <unordered_map>

//! Macro continuation aligned right
#define LOG_VERBOSE_DATA(sender, msg)                                              \
    std::cerr << "Verbose: " << sender;                                            \
    std::cerr << msg;                                                              \
    std::cerr << "End of transmission";

#define EXTREMELY_LONG_IDENTIFIER_NAME "FallbackValue" //! Consecutive macro alignment
#define SHORT_ID                    "Active"
#define CALC_RATE(x, y, z, w)       ((x) * (y) + (z) - (w))

#ifndef CONFIG_ENABLED //! Macro indentation
    #define CONFIG_ENABLED 1
    #if (CONFIG_ENABLED == 1)
    #else
        #define CONFIG_DISABLED
    #endif
#endif

int highly_extended_variable_identifier = 42;  //! Consecutive assignment alignment
int brief_var                           = 1024;
int counter_x                           = 0;

std::string path_config         = "/usr/local";
std::string path_config_alt     = "/opt/bin";
std::string path_config_runtime = "/var/run";

namespace CoreEngine {

namespace {

using std::cerr; //! using declaration sorting
using std::deque;
using std::exception;
using std::list;
using std::string;
using std::unordered_map;

enum class Status { Active, Paused, Terminated } current_status;

template <typename DataPayload> //! Template declaration break
int
process_data (int primary_id, //! Block indent when parameters exceed line limit
              int secondary_id,
              int deeply_nested_configuration_identifier_for_cluster_node)
{
    int resource_allocation_block_identifier;                     // Comment alignment
    int resource_allocation_block_identifier_v2;                  // Another comment
    int resource_allocation_block_identifier_v3;                  // Third comment
    return process_data (                                        // Mid-call comment
        resource_allocation_block_identifier,                    // Argument comment
        resource_allocation_block_identifier_v2,
        resource_allocation_block_identifier_v3_with_suffix); // End comment
}

void
initialize_subsystem ();

unordered_map<list<deque<int>>, list<unordered_map<string, int>>>> //! Return type on own line
fetch_metrics (int node_id, int timeout_ms)
{ //! Brace broken open
}

class Processor {
    class {
    public:
        int buffer_size;
    private:
    };

public:
    void execute ()

    {
        cerr << "Executing" << std::endl;
    }
private:
};

}
} //! Namespace end comment removed

using namespace CoreEngine;

int
main (int argc, char **argv)
{
    try {

        for (;;) {
            if (active && !paused || restarting) {
                cerr << "System running" << std::endl;
            } else {
                cerr << "System halted" << std::endl;
            }
            if (shutdown_requested)
                return EXIT_SUCCESS;
            else
                return EXIT_FAILURE;
        }

    } catch (...) {
        do {
            cerr << "Fallback loop" << std::endl;
        } while (true);
    }
}

void
setup_network ()
{
} //! Auto empty line between definitions

void
teardown_network ()
{
}

void
reset_state ()
{
}

void
validate_inputs ()
{
}

void
flush_buffers ()
{
}

void
terminate_handler ()
{
}

Save the configuraton as /.clang-format (ansure UTF-8 encoding).
Apply using: clang-format -style=file:/.clang-format -i <filename>

---
BasedOnStyle: Microsoft
Language: Cpp
ColumnLimit: 120

# Brace wrapping behavior
BreakBeforeBraces: Custom
BraceWrapping:
  AfterClass: false
  AfterEnum: false
  AfterExternBlock: false
  AfterStruct: false
  AfterUnion: false
  AfterNamespace: false
  AfterControlStatement: false # if, for, while, switch
  BeforeWhile: false # do-while on same line
  BeforeElse: false # else on same line
  BeforeCatch: false
  SplitEmptyFunction: true # Break empty function braces
  SplitEmptyRecord: true # Break empty class braces
  SplitEmptyNamespace: true # Break empty namespace braces
AlwaysBreakAfterReturnType: TopLevel # Return type on own line, except inside classes
BreakConstructorInitializers: AfterColon # Break initializer list
BreakInheritanceList: AfterComma # Break inheritance

# Spacing configurations
SpaceBeforeParens: Custom
SpaceBeforeParensOptions:
  AfterControlStatements: true
  AfterFunctionDefinitionName: true
  AfterFunctionDeclarationName: true
  AfterOverloadedOperator: true # Space after postfix ++
  BeforeNonEmptyParentheses: true # Space before non-empty calls

SpaceInEmptyBlock: true # Space inside empty braces (ignored if broken)
SpaceBeforeCpp11BracedList: true # Space before braced init list
SpaceAroundPointerQualifiers: Both # Pointer asterisk attachment

EmptyLineAfterAccessModifier: Leave # Preserve empty line after access modifier
EmptyLineBeforeAccessModifier: Leave # Preserve empty line before access modifier

IndentExternBlock: NoIndent # Indent extern "C" with spaces
IndentPPDirectives: BeforeHash # Macro indentation style
IndentAccessModifiers: false # Do not indent access modifiers
AccessModifierOffset: -4 # Align access modifiers to far left

BinPackArguments: false # Arguments either all on one line or all on separate lines
BinPackParameters: false # Parameters either all on one line or all on separate lines

AllowShortEnumsOnASingleLine: true # Allow single-line enums
AllowShortBlocksOnASingleLine: false # Disallow single-line braces
AllowAllParametersOfDeclarationOnNextLine: true # Allow parameters on next line
AllowAllArgumentsOnNextLine: true # Allow arguments on next line
PackConstructorInitializers: NextLine # Move initializers to next line if they don't fit, and break

# Alignment rules
AlignConsecutiveAssignments: Consecutive # Align consecutive assignments
AlignConsecutiveMacros: AcrossEmptyLines # Align consecutive macros
AlignTrailingComments: true # Align trailing comments
AlignEscapedNewlines: Right # Right-align macro backslashes

AlwaysBreakTemplateDeclarations: Yes # Break template declarations

IncludeBlocks: Regroup # Group and sort quotes vs angle brackets
FixNamespaceComments: true # Do not add closing namespace comments
SeparateDefinitionBlocks: Always # Add empty lines between definition blocks

MaxEmptyLinesToKeep: 2 # Maximum consecutive empty lines

AlignAfterOpenBracket: BlockIndent # Break both opening and closing parentheses

# Penalty configurations
# PenaltyExcessCharacter: 10
# PenaltyBreakBeforeFirstCallParameter: 0
# PenaltyBreakOpenParenthesis: 1

# PenaltyBreakAssignment: 100
# PenaltyBreakFirstLessLess: 100

# PenaltyBreakComment: 99999
# PenaltyBreakString: 99999
# PenaltyIndentedWhitespace: 0

# PenaltyBreakTemplateDeclaration: 100
# PenaltyReturnTypeOnItsOwnLine: 100

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.