![]() |
Kodi Documentation 22.0
Kodi is an open source media player and entertainment hub.
|
When working in a large group, the two most important values are readability and maintainability. We code for other people, not computers. To accomplish these goals, we have created a unified set of code conventions.
In the repository root directory, there is a .clang-format
file that implements the rules as specified here. You are encouraged to run clang-format
on any newly created files. It is currently not recommended to do so on preexisting files because all the formatting changes will clutter your commits and pull request.
When you create a pull request, the PR build job will run clang-format
on your commits and provide patches for any parts that don't satisfy the current .clang-format
rules. You should apply these patches and amend your pull request accordingly.
The coding guidelines should be met by every code change, be it editing existing code, adding new code to existing source files, or adding completely new source files. For changes in existing files, at least the changed code needs to pass the clang-format check.
Conventions can be bent or broken in the interest of making code more readable and maintainable. However, if you submit a patch that contains excessive style conflicts, you may be asked to improve your code before your pull request is reviewed.
back to top
We currently target the C++17 language standard. Do use C++17 features when possible (and supported by all target platforms). Do not use C++20 features.
back to top
The ColumnLimit
in .clang-format
is set to 100
which defines line length (in general where lines should be broken) that allows two editors side by side on a 1080p screen for diffs.
Curly braces always go on a new line.
Use spaces as tab policy with an indentation size of 2. Opening curly braces increase the level of indentation. Closing curly braces decrease the level of indentation.
Exception: Do not indent namespaces to simplify nesting them and wrapping .cpp files in a namespace.
Insert a new line before every:
Put the consequent on a new line if not in curly braces anyway. Keep else if
statements on one line. Do not put a condition and a following statement on a single line.
✅ Good:
❌ Bad:
Conventional operators have to be surrounded by one space on each side.
Control statement keywords have to be separated from opening parentheses by one space.
When conditions are used without parentheses, it is preferable to add a new line, to make the next block of code more readable.
Commas have to be followed by one space.
Initializer lists have one space after each element (including comma), but no surrounding spaces.
Do not use whitespace to vertically align around operators or values. This causes problems on code review if one needs to realign all values to their new position, producing unnecessarily large diffs.
✅ Good:
❌ Bad:
void
Do not write void
in empty function parameter declarations.
✅ Good:
❌ Bad:
There are some special situations where vertical alignment and longer lines does greatly aid readability, for example the initialization of some table-like multiple row structures. In these rare cases exceptions can be made to the formatting rules on vertical alignment, and the defined line length can be exceeded.
To prevent the layout from being reformatted, tell clang-format
to disable formatting on that section of code by surrounding it with the special comments // clang-format off
and // clang-format on
. For example:
The other code guidelines will still need to be applied within the delimited lines of code, but with clang-format
off care will be needed to check these manually. Using vertical alignment means that sometimes the entire block of code may need to be realigned, good judgement should be used in each case with the objective of preserving readability yet minimising impact.
This is to be used with discretion, marking large amounts of code to be left unformatted by clang-format
without reasonable justification will be rejected.
back to top
Do not put multiple statements on a single line. Always use a new line for a new statement. It is much easier to debug if one can pinpoint a precise line number.
✅ Good:
❌ Bad:
switch
default caseIn every switch
structure, always include a default
case, unless switching on an enum and all enum values are explicitly handled.
back to top
Always declare a variable close to its use and not before a block of code that does not use it.
✅ Good:
❌ Bad:
Do not put multiple declarations on a single line. This avoids confusion with differing pointers, references, and initialization values on the same line (cf. ISO C++ guidelines).
✅ Good:
❌ Bad:
Left-align *
and &
to the base type they modify.
✅ Good:
❌ Bad:
(This is adopted from the HP C++ Coding Guidelines: "The characters * and & are to be written with the type of variables instead of with the name of variables in order to emphasize that they are part of the type definition.")
const
and other modifiersPlace const
and similar modifiers in front of the type they modify.
✅ Good:
❌ Bad:
Make sure that variables are initialized appropriately at declaration or soon afterwards. This is especially important for fundamental type variables that do not have any constructor. Zero-initialize with {}
.
✅ Good:
❌ Bad:
We allow variable initialization using any of the C++ forms {}
, =
or ()
.
However, we would like to point out some optional suggestions to follow:
{}
form to others, because this permits explicit type checking to avoid unwanted narrowing conversions.{}
form when initializing a class/struct variable.back to top
Try to put all code into appropriate namespaces (e.g. following directory structure) and avoid polluting the global namespace.
Put functions local to a compilation unit into an anonymous namespace.
✅ Good:
❌ Bad:
back to top
Included header files have to be sorted (case sensitive) alphabetically to prevent duplicates and allow better overview, with an empty line clearly separating sections.
Header order has to be:
If the headers aren't sorted, either do your best to match the existing order, or precede your commit with an alphabetization commit.
If possible, avoid including headers in another header. Instead, you can forward-declare the class and use a std::unique_ptr
(or similar):
To use C symbols use C++ wrappers headers, by using the std
namespace prefix.
✅ Good:
❌ Bad:
back to top
Use upper case with underscores.
Use upper case with underscores.
Use PascalCase for the enum name and upper case with underscores for the values.
Use PascalCase and prefix with an uppercase I. Filename has to match the interface name without the prefixed I, e.g. Logger.h
Use PascalCase and prefix with an uppercase C. Filename has to match the class name without the prefixed C, e.g. Logger.cpp
Use PascalCase.
Use PascalCase always, uppercasing the first letter even if the methods are private or protected. Method parameters start with lower case and follow CamelCase style, without type prefixing (Systems Hungarian notation).
Variables start with lower case and follow CamelCase style. Type prefixing (Systems Hungarian notation) is discouraged.
✅ Good:
❌ Bad:
Prefix non-static member variables with m_
. Prefix static member variables with ms_
.
Prefix global variables with g_
back to top
Use //
for inline single-line and multi-line comments. Use /* */
for the copyright comment at the beginning of the file. SPDX license headers are required for all code files (see example below).
✅ Good:
❌ Bad:
New classes and functions are expected to have Doxygen comments describing their purpose, parameters, and behavior in the header file. However, do not describe trivialities - it only adds visual noise. Use the Qt style with exclamation mark (/*! */
) and backslash for doxygen commands (e.g. \brief
).
✅ Good:
❌ Bad:
back to top
Use the provided logging function CLog::Log
. Do not log to standard output or standard error using e.g. printf
or std::cout
.
The Log
function uses the fmt library for formatting log messages. Basically, you can use {}
as placeholder for anything and list the parameters to insert after the message similarly to printf
. See here for the detailed syntax and below for an example.
✅ Good:
❌ Bad:
The predefined logging levels are DEBUG
, INFO
, WARNING
, ERROR
, and FATAL
. Use anything INFO
and above sparingly since it will be written to the log by default. Too many messages will clutter the log and reduce visibility of important information. DEBUG
messages are only written when debug logging is enabled.
Make class data members private
. Think twice before using protected
for data members and functions, as its level of encapsulation is effectively equivalent to public
.
Try to mark member functions of classes as const
whenever reasonable.
When overriding virtual functions of a base class, add the override
keyword. Do not add the virtual
keyword.
✅ Good:
❌ Bad:
Use default member initialization instead of initializer lists or constructor assignments whenever it makes sense.
A class with any virtual functions should have a destructor that is either public and virtual or else protected and non-virtual (cf. ISO C++ guidelines).
For lines up to line length everything stays on one line, excluding the braces which must be on the following lines.
For longer lines, insert a line break before the colon and/or after the comma.
For functions that have multiple output values, prefer using a struct
or tuple
return value over output parameters that use pointers or references (cf. ISO C++ guidelines). In general, try to avoid output parameters completely (cf. ISO C++ guidelines, Google C++ Style Guide). At the function call site, it is completely invisible that actually a reference is being passed and the value might be modified. Return semantics make it clear what is happening.
New code has to use C++ style casts and not older C style casts. When modifying existing code the developer can choose to update it to C++ style casts or leave as is. Whenever a dynamic_cast
is used to cast to a pointer type, the result can be nullptr
and needs to be checked accordingly.
✅ Good:
❌ Bad:
NULL
vs nullptr
Prefer the use of nullptr
instead of NULL
. nullptr
is a typesafe version and as such can't be implicitly converted to int
or anything else.
auto
Feel free to use auto
wherever it improves readability, without abusing it when it is not the case.
✅ Good:
❌ Bad:
for
loopsUse range-based for loops wherever it makes sense. If iterators are used, see above about using auto
.
Remove const
if the value has to be modified. Do not use references to fundamental types that are not modified.
In traditional for loops, for the increment statement
of the loop, use prefix increment/decrement operator, not postfix.
✅ Good:
❌ Bad:
Use #pragma once
.
✅ Good:
❌ Bad:
Use the C++ using
syntax when aliasing types (encouraged when it improves readability).
✅ Good:
❌ Bad:
goto
Usage of goto
is discouraged.
Try to avoid using C macros. In many cases, they can be easily substituted with other non-macro constructs.
constexpr
Prefer constexpr
over const
for constants when possible. Try to mark functions constexpr
when reasonable.
std::string
vs std::string_view
Prefer std::string_view
over std::string
when reasonable. Good examples are constants or method arguments. In the latter case, it is not required to declare the argument as reference or const, since the data source of string views are immutable by definition. A bad example is when you need a NUL-terminated C string, e.g. to interact with a C API. std::string_view
does not offer a c_str()
function like std::string
does, but if you do not need a C string you can use data()
to get the raw source of the data.
Main reasons why we prefer std::string_view
are: execution performance, no memory allocations, substrings can be made without copy, and the possibility to reuse the same data without reallocation.
Avoid using std::string_view
when you are not sure where the source of data is allocated, or as return value of a method. If not handled properly, the source (storage) of the data may go out of scope. As a consequence, the program enters undefined behavior and may crash, behave strangely, or introduce potential security issues.
✅ Good:
❌ Bad:
back to top