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. Multiple declarations](#51-multiple-declarations)
20 * [5.2. Pointer and reference types](#52-pointer-and-reference-types)
21 * [5.3. const and other modifiers](#53-const-and-other-modifiers)
22 * [5.4. Initialization](#54-initialization)
23 * [6. Scoping](#6-scoping)
24 * [6.1. Namespaces](#61-namespaces)
25 * [6.2. Local functions](#62-local-functions)
26 * [7. Headers](#7-headers)
27 * [8. Naming](#8-naming)
28 * [8.1. Namespaces](#81-namespaces)
29 * [8.2. Constants](#82-constants)
30 * [8.3. Enums](#83-enums)
31 * [8.4. Interfaces](#84-interfaces)
32 * [8.5. Classes](#85-classes)
33 * [8.6. Methods](#86-methods)
34 * [8.7. Variables](#87-variables)
35 * [Member variables](#member-variables)
36 * [Global variables](#global-variables)
37 * [9. Comments](#9-comments)
38 * [9.1. General](#91-general)
39 * [9.2. Doxygen](#92-doxygen)
40 * [10. Logging](#10-logging)
41 * [11. Classes](#11-classes)
42 * [11.1. Member visibility](#111-member-visibility)
43 * [11.2. Const correctness](#112-const-correctness)
44 * [11.3. Overriding virtual functions](#113-overriding-virtual-functions)
45 * [11.4. Default member initialization](#114-default-member-initialization)
46 * [11.5. Destructors in interfaces](#115-destructors-in-interfaces)
47 * [11.6. Constructor Initialization Lists](#116-constructor-initialization-lists)
48 * [12. Other conventions](#12-other-conventions)
49 * [12.1. Output parameters](#121-output-parameters)
50 * [12.2. Casts](#122-casts)
51 * [12.3. `NULL` vs `nullptr`](#123-null-vs-nullptr)
52 * [12.4. auto](#124-auto)
53 * [12.5. `for` loops](#125-for-loops)
54 * [12.6. Include guards](#126-include-guards)
55 * [12.7. Type aliases](#127-type-aliases)
56 * [12.8. `goto`](#128goto)
57 * [12.9. Macros](#129-macros)
58 * [12.10. constexpr](#1210-constexpr)
61 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.
63 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.
65 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.
67 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.
69 **[back to top](#table-of-contents)**
71 ## 2. Language standard
73 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.
75 **[back to top](#table-of-contents)**
80 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.
83 Curly braces always go on a new line.
86 for (int i = 0; i < t; i++)
103 Use spaces as tab policy with an indentation size of 2.
104 Opening curly braces increase the level of indentation. Closing curly braces decrease the level of indentation.
106 **Exception:** Do not indent namespaces to simplify nesting them and wrapping *.cpp* files in a namespace.
117 virtual void Log(...) = 0;
118 virtual ~ILogger() {}
125 ### 3.3. Control statements
126 Insert a new line before every:
127 * else in an if statement
128 * catch in a try statement
129 * while in a do statement
132 Put the consequent on a new line if not in curly braces anyway. Keep `else if` statements on one line.
150 #### 3.3.2. switch case
168 #### 3.3.3. try catch
175 catch (std::exception& e)
187 Conventional operators have to be surrounded by one space on each side.
191 Control statement keywords have to be separated from opening parentheses by one space.
194 for (int i = 0; i < x; i++);
196 Commas have to be followed by one space.
198 void Dummy::Method(int a, int b, int c);
200 Initializer lists have one space after each element (including comma), but no surrounding spaces.
202 constexpr int aNiceArray[] = {1, 2, 3};
205 ### 3.5. Vertical alignment
206 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.
212 CExampleClass* exampleClass{};
213 CBiggerExampleClass* biggerExampleClass{};
214 exampleClass = new CExampleClass(value1, value2);
215 biggerExampleClass = new CBiggerExampleClass(value1, value2);
216 exampleClass->InitExample();
217 biggerExampleClass->InitExample();
225 CExampleClass *exampleClass {};
226 CBiggerExampleClass *biggerExampleClass {};
228 exampleClass = new CExampleClass (value1, value2);
229 biggerExampleClass = new CBiggerExampleClass(value1, value2);
231 exampleClass ->InitExample();
232 biggerExampleClass->InitExample();
235 ### 3.6. Superfluous `void`
237 Do not write `void` in empty function parameter declarations.
249 ### 3.7. Exceptions to the Formatting Rules For Better Readability
250 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.
252 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`.
256 static const CGUIDialogMediaFilter::Filter filterList[] = {
257 { "movies", FieldTitle, 556, SettingType::String, "edit", "string", CDatabaseQueryRule::OPERATOR_CONTAINS },
258 { "movies", FieldRating, 563, SettingType::Number, "range", "number", CDatabaseQueryRule::OPERATOR_BETWEEN },
259 { "movies", FieldUserRating, 38018, SettingType::Integer, "range", "integer", CDatabaseQueryRule::OPERATOR_BETWEEN },
261 { "songs", FieldSource, 39030, SettingType::List, "list", "string", CDatabaseQueryRule::OPERATOR_EQUALS },
265 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.
267 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.
269 **[back to top](#table-of-contents)**
273 ### 4.1. Multiple statements
274 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.
278 std::vector<std::string> test;
279 test.push_back("foobar");
284 std::vector<std::string> test; test.push_back("foobar");
287 ### 4.2. `switch` default case
289 In every `switch` structure, always include a `default` case, unless switching on an enum and all enum values are explicitly handled.
291 **[back to top](#table-of-contents)**
295 ### 5.1. Multiple declarations
296 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)).
309 ### 5.2. Pointer and reference types
310 Left-align `*` and `&` to the base type they modify.
315 void test(const std::string& b);
322 void test(const std::string &b);
325 (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.")
327 ### 5.3. `const` and other modifiers
328 Place `const` and similar modifiers in front of the type they modify.
332 void Test(const std::string& a);
333 const int* const someIntPointer;
338 void Test(std::string const& a);
339 int const * const someIntPointer;
342 ### 5.4. Initialization
344 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 `{}`.
350 CLog::Log("test: {} {}", x, y);
355 int x; // used uninitialized
356 int* y = nullptr; // default-initialization not using {}
357 CLog::Log("test: {} {}", x, y);
360 In general, prefer the `{}` initializer syntax over alternatives. This syntax is less ambiguous and disallows narrowing (cf. [ISO C++ guidelines](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-list)).
368 **[back to top](#table-of-contents)**
374 Try to put all code into appropriate namespaces (e.g. following directory structure) and avoid polluting the global namespace.
376 ### 6.2. Local functions
378 Put functions local to a compilation unit into an anonymous namespace.
395 **[back to top](#table-of-contents)**
398 Included header files have to be sorted (case sensitive) alphabetically to prevent duplicates and allow better overview, with an empty line clearly separating sections.
400 Header order has to be:
402 * Other Kodi includes (platform independent)
403 * Other Kodi includes (platform specific)
404 * C and C++ system files
405 * Other libraries' header files
406 * special Kodi headers (PlatformDefs.h, system.h and system_gl.h)
409 #include "PVRManager.h"
411 #include "Application.h"
412 #include "ServiceBroker.h"
413 #include "addons/AddonInstaller.h"
414 #include "dialogs/GUIDialogExtendedProgressBar.h"
415 #include "messaging/ApplicationMessenger.h"
416 #include "messaging/ThreadMessage.h"
417 #include "messaging/helpers/DialogHelper.h"
418 #include "music/MusicDatabase.h"
419 #include "music/tags/MusicInfoTag.h"
420 #include "network/Network.h"
421 #include "pvr/addons/PVRClients.h"
422 #include "pvr/channels/PVRChannel.h"
423 #include "settings/Settings.h"
424 #include "threads/SingleLock.h"
425 #include "utils/JobManager.h"
426 #include "utils/Variant.h"
427 #include "utils/log.h"
428 #include "video/VideoDatabase.h"
433 #include <libavutil/pixfmt.h>
436 If the headers aren't sorted, either do your best to match the existing order, or precede your commit with an alphabetization commit.
438 If possible, avoid including headers in another header. Instead, you can forward-declare the class and use a `std::unique_ptr` (or similar):
446 std::unique_ptr<CFileItem> m_fileItem;
450 **[back to top](#table-of-contents)**
454 Use upper case with underscores.
463 Use upper case with underscores.
465 constexpr int MY_CONSTANT = 1;
469 Use PascalCase for the enum name and upper case with underscores for the values.
479 Use PascalCase and prefix with an uppercase I. Filename has to match the interface name without the prefixed I, e.g. Logger.h
484 virtual void Log(...) = 0;
485 virtual ~ILogger() {}
490 Use PascalCase and prefix with an uppercase C. Filename has to match the class name without the prefixed C, e.g. Logger.cpp
492 class CLogger : public ILogger
495 void Log(...) override;
500 Use PascalCase always, uppercasing the first letter even if the methods are private or protected.
502 void MyDummyClass::DoSomething();
506 Use CamelCase. Type prefixing (Systems Hungarian notation) is discouraged.
508 #### Member variables
509 Prefix non-static member variables with `m_`. Prefix static member variables with `ms_`.
512 static int ms_variableB;
515 #### Global variables
516 Prefix global variables with `g_`
518 int g_globalVariableA;
520 **WARNING:** Avoid use of globals as far as reasonably possible. We generally do not want to introduce new global variables.
522 **[back to top](#table-of-contents)**
528 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).
533 * Copyright (C) 2005-2018 Team Kodi
534 * This file is part of Kodi - https://kodi.tv
536 * SPDX-License-Identifier: GPL-2.0-or-later
537 * See LICENSES/README.md for more information.
542 // This can also continue for multiple lines:
543 // I am the second line.
554 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`).
559 * \brief Splits the given input string using the given delimiter into separate strings.
561 * If the given input string is empty, nothing will be put into the target iterator.
563 * \param destination the beginning of the destination range
564 * \param input input string to be split
565 * \param delimiter delimiter to be used to split the input string
566 * \param maxStrings (optional) maximum number of splitted strings
567 * \return output iterator to the element in the destination range one past the last element
570 template<typename OutputIt>
571 static OutputIt SplitTo(OutputIt destination, const std::string& input, const std::string& delimiter, unsigned int maxStrings = 0);
577 * @brief Function for documentation purposes (javadoc style)
581 void ReallyComplicatedFunction(); // does something really complicated
584 * \brief Frobnicate a parameter
585 * \param param parameter to frobnicate
586 * \result frobnication result
588 int Frobnicate(int param);
591 **[back to top](#table-of-contents)**
595 Use the provided logging function `CLog::Log`. Do not log to standard output or standard error using e.g. `printf` or `std::cout`.
597 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.
601 CLog::Log(LOGDEBUG, "Window size: {}x{}", width, height);
606 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
607 printf("Window size: %dx%d", width, height);
608 std::cout << "Window size: " << width << "x" << height << std::endl;
611 The predefined logging levels are `DEBUG`, `INFO`, `NOTICE`, `WARNING`, `ERROR`, `SEVERE`, 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.
615 ### 11.1. Member visibility
617 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`.
619 ### 11.2. Const correctness
621 Try to mark member functions of classes as `const` whenever reasonable.
623 ### 11.3. Overriding virtual functions
625 When overriding virtual functions of a base class, add the `override` keyword. Do not add the `virtual` keyword.
629 class CLogger : public ILogger
632 void Log(...) override;
638 class CLogger : public ILogger
641 virtual void Log(...) override;
645 ### 11.4. Default member initialization
646 Use default member initialization instead of initializer lists or constructor assignments whenever it makes sense.
654 ### 11.5. Destructors in interfaces
656 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)).
658 ### 11.6. Constructor Initialization Lists
660 For lines up to [line length](#line-length) everything stays on one line, excluding the braces which must be on the following lines.
663 MyClass::CMyClass(bool bBoolArg, int iIntegerArg) : m_bArg(bBoolArg), m_iArg(iIntegerArg)
668 For longer lines, break before colon and after comma.
671 MyClass::CMyClass(bool bBoolArg,
673 const std::string& strSomeText,
674 const std::shared_ptr<CMyOtherClass>& myOtherClass)
675 : m_bBoolArg(bBoolArg),
676 m_iIntegerArg(iIntegerArg),
677 m_strSomeText(strSomeText),
678 m_myOtherClass(myOtherClass)
683 ## 12. Other conventions
685 ### 12.1. Output parameters
686 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.
689 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.
691 ### 12.3. `NULL` vs `nullptr`
692 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.
696 Feel free to use `auto` wherever it improves readability, which is not always the case. Good places are iterators or when dealing with containers. Bad places are code that expects a certain type that is not immediately clear from the context.
700 auto i = var.begin();
702 std::vector<CSizeInt> list;
703 for (const auto j : list)
711 std::map<std::string, std::vector<int>>::iterator i = var.begin();
714 ### 12.5. `for` loops
715 Use range-based for loops wherever it makes sense. If iterators are used, see above about using `auto`.
717 for (const auto& : var)
722 Remove `const` if the value has to be modified. Do not use references to fundamental types that are not modified.
724 ### 12.6. Include guards
735 #ifndef SOME_FILE_H_INCLUDED
736 #define SOME_FILE_H_INCLUDED
741 ### 12.7. Type aliases
743 Use the C++ `using` syntax when aliasing types (encouraged when it improves readability).
747 using SizeType = int;
752 typedef int SizeType;
757 Usage of `goto` is discouraged.
761 Try to avoid using C macros. In many cases, they can be easily substituted with other non-macro constructs.
763 ### 12.10. `constexpr`
765 Prefer `constexpr` over `const` for constants when possible. Try to mark functions `constexpr` when reasonable.
767 **[back to top](#table-of-contents)**