Configuring Clang-Format for K&R C/C++ Style
cpp #include "custom_driver.h" #include "system_bus.h"
#include #include #include #include //! 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 <typenmae 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 commment }
void initialize_subsystem ();
unordered_map<list<deque>, 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 configuration as /.clang-format (ensure UTF-8 encoding).
Apply using: clang-format -style=file:/.clang-format -i <filename>
yaml
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 samme 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