metal-kompanion/resources/kde-cpp-style.md

2.5 KiB
Raw Blame History

KDE C++ Coding Style

Indentation and Whitespace

  • Use spaces only for indentation; no tabs. KDE uses four spaces per indent level.
  • Declare each variable on its own line and use camelCase names; avoid abbreviations and meaningless names.
  • Insert blank lines to group logical blocks, but never leave more than one empty line in a row.
  • Put a space after control keywords (if, for, while) and after commas, and put spaces around binary operators like +, -, * or %; avoid spaces inside parentheses.
  • For pointers and references, place the * or & next to the type, not the variable name.

Braces and Control Flow

  • Use the K&R attached brace style: the opening brace goes on the same line as the if, for or while statement.
  • Always use curly braces, even when a conditional or loop body contains only one statement.
  • In an if-else chain, place else on the same line as the closing brace (} else {).
  • For function implementations, class/struct/namespace declarations, place the opening brace on a new line.
  • Keep case labels aligned with the switch statement; indent the statements within each case block.

Naming Conventions

  • Variables and functions use camelCase starting with a lowercase letter; classes and structs use CamelCase starting with an uppercase letter.
  • Prefix private member variables with m_ and static or file-scope variables with s_.
  • Avoid meaningless names; single-character names are reserved for loop indices and obvious temporaries.
  • Boolean getters should read naturally (e.g. isEmpty(), hasSelection()) rather than using get prefixes.

Includes and File Structure

  • In implementation files, group includes in this order: the classs own header, other headers from the same framework, headers from other frameworks, Qt headers, then other system or standard headers. Separate groups with blank lines and sort each group alphabetically.
  • When including Qt or KDE classes, omit the module prefix (e.g. use <QString> rather than <QtCore/QString>).
  • Header files must have an include guard based on the file name in all capitals with underscores and no leading or trailing underscore.

Automatic Formatting Tools

  • KDE provides scripts such as astyle-kdelibs to reformat code using Artistic Style; this script enforces four-space indentation and K&R braces.
  • A standard .clang-format file is distributed with KDE frameworks; projects can add a kde_clang_format target and use a Git pre-commit hook to automatically format code.