3 ![Kodi Logo](https://github.com/xbmc/xbmc/raw/master/docs/resources/banner_slim.png)
6 * [1. Motivation](#1-motivation)
7 * [2. Language standard](#2-language-standard)
8 * [3. Formatting](#3-formatting)
9 * [3.1. Braces](#31-braces)
10 * [3.2. Indentation](#32-indentation)
11 * [3.3. Control statements](#33-control-statements)
12 * [3.3.1. if else](#331-if-else)
13 * [3.3.2. switch case](#332-switch-case)
14 * [3.3.3. try catch](#333-try-catch)
15 * [3.4. Whitespace](#34-whitespace)
16 * [3.5. Vertical alignment](#35-vertical-alignment)
17 * [4. Statements](#4-statements)
18 * [5. Declarations](#5-declarations)
19 * [5.1. Declarations](#51-declarations)
20 * [5.2. Multiple declarations](#52-multiple-declarations)
21 * [5.3. Pointer and reference types](#53-pointer-and-reference-types)
22 * [5.4. const and other modifiers](#54-const-and-other-modifiers)
23 * [5.5. Initialization](#55-initialization)
24 * [6. Scoping](#6-scoping)
25 * [6.1. Namespaces](#61-namespaces)
26 * [6.2. Local functions](#62-local-functions)
27 * [7. Headers](#7-headers)
28 * [7.1. Header order](#71-header-order)
29 * [7.2. Use C++ wrappers for C headers](#72-use-c-wrappers-for-c-headers)
30 * [8. Naming](#8-naming)
31 * [8.1. Namespaces](#81-namespaces)
32 * [8.2. Constants](#82-constants)
33 * [8.3. Enums](#83-enums)
34 * [8.4. Interfaces](#84-interfaces)
35 * [8.5. Classes](#85-classes)
36 * [8.6. Structs](#86-structs)
37 * [8.7. Methods](#87-methods)
38 * [8.8. Variables](#88-variables)
39 * [Member variables](#member-variables)
40 * [Global variables](#global-variables)
41 * [9. Comments](#9-comments)
42 * [9.1. General](#91-general)
43 * [9.2. Doxygen](#92-doxygen)
44 * [10. Logging](#10-logging)
45 * [11. Classes](#11-classes)
46 * [11.1. Member visibility](#111-member-visibility)
47 * [11.2. Const correctness](#112-const-correctness)
48 * [11.3. Overriding virtual functions](#113-overriding-virtual-functions)
49 * [11.4. Default member initialization](#114-default-member-initialization)
50 * [11.5. Destructors in interfaces](#115-destructors-in-interfaces)
51 * [11.6. Constructor Initialization Lists](#116-constructor-initialization-lists)
52 * [12. Other conventions](#12-other-conventions)
53 * [12.1. Output parameters](#121-output-parameters)
54 * [12.2. Casts](#122-casts)
55 * [12.3. `NULL` vs `nullptr`](#123-null-vs-nullptr)
56 * [12.4. auto](#124-auto)
57 * [12.5. `for` loops](#125-for-loops)
58 * [12.6. Include guards](#126-include-guards)
59 * [12.7. Type aliases](#127-type-aliases)
60 * [12.8. `goto`](#128-goto)
61 * [12.9. Macros](#129-macros)
62 * [12.10. constexpr](#1210-constexpr)
63 * [12.11. `std::string` vs `std::string_view`](#1211-stdstring-vs-stdstring_view)
66 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.
68 In the repository root directory, there is a [`.clang-format`](https://github.com/xbmc/xbmc/blob/master/.clang-format) file that implements the rules as specified here. You are encouraged to run [`clang-format`](https://clang.llvm.org/docs/ClangFormat.html) 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.
70 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.
72 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.
74 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.
76 **[back to top](#table-of-contents)**
78 ## 2. Language standard
80 We currently target the C++20 language standard. Do use C++20 features when possible (and supported by all target platforms). Do not use C++23 features.
82 **[back to top](#table-of-contents)**
87 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.
90 Curly braces always go on a new line.
93 for (int i = 0; i < t; ++i)
110 Use spaces as tab policy with an indentation size of 2.
111 Opening curly braces increase the level of indentation. Closing curly braces decrease the level of indentation.
113 **Exception:** Do not indent namespaces to simplify nesting them and wrapping *.cpp* files in a namespace.
124 virtual void Log(...) = 0;
125 virtual ~ILogger() {}
132 ### 3.3. Control statements
133 Insert a new line before every:
134 * else in an if statement
135 * catch in a try statement
138 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.
162 #### 3.3.2. switch case
180 #### 3.3.3. try catch
187 catch (std::exception& e)
199 Conventional operators have to be surrounded by one space on each side.
203 Control statement keywords have to be separated from opening parentheses by one space.
206 for (int i = 0; i < x; ++i);
208 When conditions are used without parentheses, it is preferable to add a new line, to make the next block of code more readable.
215 Commas have to be followed by one space.
217 void Dummy::Method(int a, int b, int c);
219 Initializer lists have one space after each element (including comma), but no surrounding spaces.
221 constexpr int aNiceArray[] = {1, 2, 3};
224 ### 3.5. Vertical alignment
225 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.
231 CExampleClass* exampleClass{};
232 CBiggerExampleClass* biggerExampleClass{};
233 exampleClass = new CExampleClass(value1, value2);
234 biggerExampleClass = new CBiggerExampleClass(value1, value2);
235 exampleClass->InitExample();
236 biggerExampleClass->InitExample();
244 CExampleClass *exampleClass {};
245 CBiggerExampleClass *biggerExampleClass {};
247 exampleClass = new CExampleClass (value1, value2);
248 biggerExampleClass = new CBiggerExampleClass(value1, value2);
250 exampleClass ->InitExample();
251 biggerExampleClass->InitExample();
254 ### 3.6. Superfluous `void`
256 Do not write `void` in empty function parameter declarations.
268 ### 3.7. Exceptions to the Formatting Rules For Better Readability
269 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.
271 To prevent the layout from being reformatted, tell `clang-format` to [disable formatting](https://clang.llvm.org/docs/ClangFormatStyleOptions.html#disabling-formatting-on-a-piece-of-code) on that section of code by surrounding it with the special comments `// clang-format off` and `// clang-format on`.
275 static const CGUIDialogMediaFilter::Filter filterList[] = {
276 { "movies", FieldTitle, 556, SettingType::String, "edit", "string", CDatabaseQueryRule::OPERATOR_CONTAINS },
277 { "movies", FieldRating, 563, SettingType::Number, "range", "number", CDatabaseQueryRule::OPERATOR_BETWEEN },
278 { "movies", FieldUserRating, 38018, SettingType::Integer, "range", "integer", CDatabaseQueryRule::OPERATOR_BETWEEN },
280 { "songs", FieldSource, 39030, SettingType::List, "list", "string", CDatabaseQueryRule::OPERATOR_EQUALS },
284 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.
286 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.
288 **[back to top](#table-of-contents)**
292 ### 4.1. Multiple statements
293 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.
297 std::vector<std::string> test;
298 test.push_back("foobar");
303 std::vector<std::string> test; test.push_back("foobar");
306 ### 4.2. `switch` default case
308 In every `switch` structure, always include a `default` case, unless switching on an enum and all enum values are explicitly handled.
310 **[back to top](#table-of-contents)**
314 ### 5.1. Declarations
316 Always declare a variable close to its use and not before a block of code that does not use it.
321 CLog::Log("test: {}", x); // variable used just after its declaration
326 int x{3}; // variable not immediately used by the next block of code
327 [...many lines of code that do not use variable x...]
328 CLog::Log("test: {}", x);
331 ### 5.2. Multiple declarations
332 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](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es10-declare-one-name-only-per-declaration)).
345 ### 5.3. Pointer and reference types
346 Left-align `*` and `&` to the base type they modify.
351 void test(const std::string& b);
358 void test(const std::string &b);
361 (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.")
363 ### 5.4. `const` and other modifiers
364 Place `const` and similar modifiers in front of the type they modify.
368 void Test(const std::string& a);
369 const int* const someIntPointer;
374 void Test(std::string const& a);
375 int const * const someIntPointer;
378 ### 5.5. Initialization
380 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 `{}`.
387 std::string text; // not primitive
388 KindOfStruct theStruct{}; // POD structures or structures with uninitalised members must be initialised with empty brackets
389 Log::Log("test: {}, {}, {}", x, y, z);
394 int x; // used uninitialized
395 int* y = nullptr; // default-initialization not using {}
396 bool z{}; // no value explicitly declared for fundamental type, preferable for better reading
397 std::string text{}; // has its default constructor
398 Log::Log("test: {}, {}, {}", x, y, z);
401 We allow variable initialization using any of the C++ forms `{}`, `=` or `()`.
403 However, we would like to point out some optional suggestions to follow:
404 - Prefer the `{}` form to others, because this permits explicit type checking to avoid unwanted narrowing conversions.
405 - Prefer the `{}` form when initializing a class/struct variable.
406 - Specify an explicit initialization value, at least for fundamental types.
408 **[back to top](#table-of-contents)**
414 Try to put all code into appropriate namespaces (e.g. following directory structure) and avoid polluting the global namespace.
416 ### 6.2. Local functions
418 Put functions local to a compilation unit into an anonymous namespace.
427 } // unnamed namespace
435 **[back to top](#table-of-contents)**
438 ### 7.1. Header order
439 Included header files have to be sorted (case sensitive) alphabetically to prevent duplicates and allow better overview, with an empty line clearly separating sections.
441 Header order has to be:
443 * Other Kodi includes (platform independent)
444 * Other Kodi includes (platform specific)
445 * C and C++ system files
446 * Other libraries' header files
447 * special Kodi headers (PlatformDefs.h, system.h and system_gl.h)
450 #include "PVRManager.h"
452 #include "Application.h"
453 #include "ServiceBroker.h"
454 #include "addons/AddonInstaller.h"
455 #include "dialogs/GUIDialogExtendedProgressBar.h"
456 #include "messaging/ApplicationMessenger.h"
457 #include "messaging/ThreadMessage.h"
458 #include "messaging/helpers/DialogHelper.h"
459 #include "music/MusicDatabase.h"
460 #include "music/tags/MusicInfoTag.h"
461 #include "network/Network.h"
462 #include "pvr/addons/PVRClients.h"
463 #include "pvr/channels/PVRChannel.h"
464 #include "settings/Settings.h"
465 #include "threads/SingleLock.h"
466 #include "utils/JobManager.h"
467 #include "utils/Variant.h"
468 #include "utils/log.h"
469 #include "video/VideoDatabase.h"
474 #include <libavutil/pixfmt.h>
477 If the headers aren't sorted, either do your best to match the existing order, or precede your commit with an alphabetization commit.
479 If possible, avoid including headers in another header. Instead, you can forward-declare the class and use a `std::unique_ptr` (or similar):
487 std::unique_ptr<CFileItem> m_fileItem;
491 ### 7.2. Use C++ wrappers for C headers
492 To use C symbols use C++ wrappers headers, by using the `std` namespace prefix.
498 size_t n = std::strlen(str);
503 #include <string.h> // C header
505 size_t n = strlen(str); // missing std namespace
508 **[back to top](#table-of-contents)**
512 Use upper case with underscores.
521 Use upper case with underscores.
523 constexpr int MY_CONSTANT = 1;
527 Use PascalCase for the enum name and upper case with underscores for the values.
537 Use PascalCase and prefix with an uppercase I. Filename has to match the interface name without the prefixed I, e.g. Logger.h
542 virtual void Log(...) = 0;
543 virtual ~ILogger() {}
548 Use PascalCase and prefix with an uppercase C. Filename has to match the class name without the prefixed C, e.g. Logger.cpp
550 class CLogger : public ILogger
553 void Log(...) override;
562 bool m_isBold{false};
567 Use PascalCase always, uppercasing the first letter even if the methods are private or protected.
568 Method parameters start with lower case and follow CamelCase style, without type prefixing (Systems Hungarian notation).
570 void MyDummyClass::DoSomething(int limitBound);
574 Variables start with lower case and follow CamelCase style. Type prefixing (Systems Hungarian notation) is discouraged.
578 bool isSunYellow{true};
583 bool bSunYellow{true}; // type prefixing
586 #### Member variables
587 Prefix non-static member variables with `m_`. Prefix static member variables with `ms_`.
590 static int ms_variableB;
593 #### Global variables
594 Prefix global variables with `g_`
596 int g_globalVariableA;
600 > Avoid use of globals as far as reasonably possible. We generally do not want to introduce new global variables.
602 **[back to top](#table-of-contents)**
608 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).
613 * Copyright (C) 2005-2018 Team Kodi
614 * This file is part of Kodi - https://kodi.tv
616 * SPDX-License-Identifier: GPL-2.0-or-later
617 * See LICENSES/README.md for more information.
622 // This can also continue for multiple lines:
623 // I am the second line.
634 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`).
639 * \brief Splits the given input string using the given delimiter into separate strings.
641 * If the given input string is empty, nothing will be put into the target iterator.
643 * \param destination the beginning of the destination range
644 * \param input input string to be split
645 * \param delimiter delimiter to be used to split the input string
646 * \param maxStrings (optional) maximum number of splitted strings
647 * \return output iterator to the element in the destination range one past the last element
650 template<typename OutputIt>
651 static OutputIt SplitTo(OutputIt destination, const std::string& input, const std::string& delimiter, unsigned int maxStrings = 0);
657 * @brief Function for documentation purposes (javadoc style)
661 void ReallyComplicatedFunction(); // does something really complicated
664 * \brief Frobnicate a parameter
665 * \param param parameter to frobnicate
666 * \result frobnication result
668 int Frobnicate(int param);
671 **[back to top](#table-of-contents)**
675 Use the provided logging function `CLog::Log`. Do not log to standard output or standard error using e.g. `printf` or `std::cout`.
677 The `Log` function uses the [fmt library](http://fmtlib.net/) 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](http://fmtlib.net/latest/syntax.html) for the detailed syntax and below for an example.
681 CLog::Log(LOGDEBUG, "Window size: {}x{}", width, height);
682 CLog::LogF(LOGERROR, "An error occurred in window \"{}\"", name); // Use helper function `CLog::LogF` to print also the name of method.
687 CLog::Log(LOGWARNING, "Window size: %dx%d", width, height); // printf-style format strings are possible, but discouraged; also the message does not warrant the warning level
688 CLog::Log(LOGERROR, "{}: An error occurred in window \"{}\"", __FUNCTION__, name); // Do not use __FUNCTION__ macro, use `CLog::LogF` instead.
689 printf("Window size: %dx%d", width, height);
690 std::cout << "Window size: " << width << "x" << height << std::endl;
693 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.
697 ### 11.1. Member visibility
699 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`.
701 ### 11.2. Const correctness
703 Try to mark member functions of classes as `const` whenever reasonable.
705 ### 11.3. Overriding virtual functions
707 When overriding virtual functions of a base class, add the `override` keyword. Do not add the `virtual` keyword.
711 class CLogger : public ILogger
714 void Log(...) override;
720 class CLogger : public ILogger
723 virtual void Log(...) override;
727 ### 11.4. Default member initialization
728 Use default member initialization instead of initializer lists or constructor assignments whenever it makes sense.
732 bool m_fooBar{false};
736 ### 11.5. Destructors in interfaces
738 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](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-dtor-virtual)).
740 ### 11.6. Constructor Initialization Lists
742 For lines up to [line length](#line-length) everything stays on one line, excluding the braces which must be on the following lines.
745 MyClass::CMyClass(bool argOne, int argTwo) : m_argOne(argOne), m_argTwo(argTwo)
750 For longer lines, insert a line break before the colon and/or after the comma.
753 MyClass::CMyClass(bool argOne,
755 const std::string& textArg,
756 const std::shared_ptr<CMyOtherClass>& myOtherClass)
760 m_myOtherClass(myOtherClass)
765 ## 12. Other conventions
767 ### 12.1. Output parameters
768 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](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-out-multi)). In general, try to avoid output parameters completely (cf. [ISO C++ guidelines](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-out), [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Output_Parameters)). 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.
771 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.
775 char m_dataChar{...};
776 uint8_t m_dataInt = static_cast<uint8_t>(m_dataChar);
781 char m_dataChar{...};
782 uint8_t m_dataInt = (uint8_t)m_dataChar;
785 ### 12.3. `NULL` vs `nullptr`
786 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.
790 Feel free to use `auto` wherever it improves readability, without abusing it when it is not the case.
791 - Good places are iterators or types that have multiple sub-levels in a namespace.
792 - Bad places are code that expects a certain type that is not immediately clear from the context, or when you declare fundamental types.
797 constexpr float START_POINT = 5;
799 auto i = var.begin();
801 std::vector<CSizeInt> list;
802 for (const auto j : list)
811 constexpr auto START_POINT = 5; // may cause problems due to wrong type deduced, many auto variables make reading difficult
813 std::map<std::string, std::vector<int>>::iterator i = var.begin();
816 ### 12.5. `for` loops
817 Use range-based for loops wherever it makes sense. If iterators are used, see above about using `auto`.
819 for (const auto& : var)
824 Remove `const` if the value has to be modified. Do not use references to fundamental types that are not modified.
826 In traditional for loops, for the `increment statement` of the loop, use prefix increment/decrement operator, not postfix.
831 for (int i = 0; i < 100; ++i)
839 for (int i = 0; i < 100; i++)
845 ### 12.6. Include guards
856 #ifndef SOME_FILE_H_INCLUDED
857 #define SOME_FILE_H_INCLUDED
862 ### 12.7. Type aliases
864 Use the C++ `using` syntax when aliasing types (encouraged when it improves readability).
868 using SizeType = int;
873 typedef int SizeType;
878 Usage of `goto` is discouraged.
882 Try to avoid using C macros. In many cases, they can be easily substituted with other non-macro constructs.
884 ### 12.10. `constexpr`
886 Prefer `constexpr` over `const` for constants when possible. Try to mark functions `constexpr` when reasonable.
888 ### 12.11. `std::string` vs `std::string_view`
890 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.
892 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.
894 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.
900 constexpr std::string_view CONSTANT_FOO{"foo-bar"};
901 } // unnamed namespace
903 void CClass::SetText(std::string_view value)
905 CLog::LogF(LOGDEBUG, "My name is {}", value);
909 SetText(CONSTANT_FOO.substr(0, 3)); // substr returns a modified view of the same string_view, thus without allocations
916 constexpr std::string CONSTANT_FOO{"foo-bar"}; // using string_view will avoid a memory allocation
917 } // unnamed namespace
919 void CClass::SetText(const std::string& value) // despite being declared as a reference, using string_view will result in a lower overhead in many cases (e.g., when passing a C string literal)
921 CLog::LogF(LOGDEBUG, "My name is {}", value);
925 SetText(CONSTANT_FOO.substr(0, 3)); // using string_view will avoid a memory allocation due to substr
928 **[back to top](#table-of-contents)**