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 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.
74 **[back to top](#table-of-contents)**
76 ## 2. Language standard
78 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.
80 **[back to top](#table-of-contents)**
85 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.
88 Curly braces always go on a new line.
91 for (int i = 0; i < t; i++)
108 Use spaces as tab policy with an indentation size of 2.
109 Opening curly braces increase the level of indentation. Closing curly braces decrease the level of indentation.
111 **Exception:** Do not indent namespaces to simplify nesting them and wrapping *.cpp* files in a namespace.
122 virtual void Log(...) = 0;
123 virtual ~ILogger() {}
130 ### 3.3. Control statements
131 Insert a new line before every:
132 * else in an if statement
133 * catch in a try statement
136 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.
160 #### 3.3.2. switch case
178 #### 3.3.3. try catch
185 catch (std::exception& e)
197 Conventional operators have to be surrounded by one space on each side.
201 Control statement keywords have to be separated from opening parentheses by one space.
204 for (int i = 0; i < x; i++);
206 When conditions are used without parentheses, it is preferable to add a new line, to make the next block of code more readable.
213 Commas have to be followed by one space.
215 void Dummy::Method(int a, int b, int c);
217 Initializer lists have one space after each element (including comma), but no surrounding spaces.
219 constexpr int aNiceArray[] = {1, 2, 3};
222 ### 3.5. Vertical alignment
223 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.
229 CExampleClass* exampleClass{};
230 CBiggerExampleClass* biggerExampleClass{};
231 exampleClass = new CExampleClass(value1, value2);
232 biggerExampleClass = new CBiggerExampleClass(value1, value2);
233 exampleClass->InitExample();
234 biggerExampleClass->InitExample();
242 CExampleClass *exampleClass {};
243 CBiggerExampleClass *biggerExampleClass {};
245 exampleClass = new CExampleClass (value1, value2);
246 biggerExampleClass = new CBiggerExampleClass(value1, value2);
248 exampleClass ->InitExample();
249 biggerExampleClass->InitExample();
252 ### 3.6. Superfluous `void`
254 Do not write `void` in empty function parameter declarations.
266 ### 3.7. Exceptions to the Formatting Rules For Better Readability
267 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.
269 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`.
273 static const CGUIDialogMediaFilter::Filter filterList[] = {
274 { "movies", FieldTitle, 556, SettingType::String, "edit", "string", CDatabaseQueryRule::OPERATOR_CONTAINS },
275 { "movies", FieldRating, 563, SettingType::Number, "range", "number", CDatabaseQueryRule::OPERATOR_BETWEEN },
276 { "movies", FieldUserRating, 38018, SettingType::Integer, "range", "integer", CDatabaseQueryRule::OPERATOR_BETWEEN },
278 { "songs", FieldSource, 39030, SettingType::List, "list", "string", CDatabaseQueryRule::OPERATOR_EQUALS },
282 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.
284 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.
286 **[back to top](#table-of-contents)**
290 ### 4.1. Multiple statements
291 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.
295 std::vector<std::string> test;
296 test.push_back("foobar");
301 std::vector<std::string> test; test.push_back("foobar");
304 ### 4.2. `switch` default case
306 In every `switch` structure, always include a `default` case, unless switching on an enum and all enum values are explicitly handled.
308 **[back to top](#table-of-contents)**
312 ### 5.1. Declarations
314 Always declare a variable close to its use and not before a block of code that does not use it.
319 CLog::Log("test: {}", x); // variable used just after its declaration
324 int x{3}; // variable not immediately used by the next block of code
325 [...many lines of code that do not use variable x...]
326 CLog::Log("test: {}", x);
329 ### 5.2. Multiple declarations
330 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)).
343 ### 5.3. Pointer and reference types
344 Left-align `*` and `&` to the base type they modify.
349 void test(const std::string& b);
356 void test(const std::string &b);
359 (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.")
361 ### 5.4. `const` and other modifiers
362 Place `const` and similar modifiers in front of the type they modify.
366 void Test(const std::string& a);
367 const int* const someIntPointer;
372 void Test(std::string const& a);
373 int const * const someIntPointer;
376 ### 5.5. Initialization
378 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 `{}`.
385 std::string text; // not primitive
386 KindOfStruct theStruct{}; // POD structures or structures with uninitalised members must be initialised with empty brackets
387 Log::Log("test: {}, {}, {}", x, y, z);
392 int x; // used uninitialized
393 int* y = nullptr; // default-initialization not using {}
394 bool z{}; // no value explicitly declared for fundamental type, preferable for better reading
395 std::string text{}; // has its default constructor
396 Log::Log("test: {}, {}, {}", x, y, z);
399 We allow variable initialization using any of the C++ forms `{}`, `=` or `()`.
401 However, we would like to point out some optional suggestions to follow:
402 - Prefer the `{}` form to others, because this permits explicit type checking to avoid unwanted narrowing conversions.
403 - Prefer the `{}` form when initializing a class/struct variable.
404 - Specify an explicit initialization value, at least for fundamental types.
406 **[back to top](#table-of-contents)**
412 Try to put all code into appropriate namespaces (e.g. following directory structure) and avoid polluting the global namespace.
414 ### 6.2. Local functions
416 Put functions local to a compilation unit into an anonymous namespace.
425 } // unnamed namespace
433 **[back to top](#table-of-contents)**
436 ### 7.1. Header order
437 Included header files have to be sorted (case sensitive) alphabetically to prevent duplicates and allow better overview, with an empty line clearly separating sections.
439 Header order has to be:
441 * Other Kodi includes (platform independent)
442 * Other Kodi includes (platform specific)
443 * C and C++ system files
444 * Other libraries' header files
445 * special Kodi headers (PlatformDefs.h, system.h and system_gl.h)
448 #include "PVRManager.h"
450 #include "Application.h"
451 #include "ServiceBroker.h"
452 #include "addons/AddonInstaller.h"
453 #include "dialogs/GUIDialogExtendedProgressBar.h"
454 #include "messaging/ApplicationMessenger.h"
455 #include "messaging/ThreadMessage.h"
456 #include "messaging/helpers/DialogHelper.h"
457 #include "music/MusicDatabase.h"
458 #include "music/tags/MusicInfoTag.h"
459 #include "network/Network.h"
460 #include "pvr/addons/PVRClients.h"
461 #include "pvr/channels/PVRChannel.h"
462 #include "settings/Settings.h"
463 #include "threads/SingleLock.h"
464 #include "utils/JobManager.h"
465 #include "utils/Variant.h"
466 #include "utils/log.h"
467 #include "video/VideoDatabase.h"
472 #include <libavutil/pixfmt.h>
475 If the headers aren't sorted, either do your best to match the existing order, or precede your commit with an alphabetization commit.
477 If possible, avoid including headers in another header. Instead, you can forward-declare the class and use a `std::unique_ptr` (or similar):
485 std::unique_ptr<CFileItem> m_fileItem;
489 ### 7.2. Use C++ wrappers for C headers
490 To use C symbols use C++ wrappers headers, by using the `std` namespace prefix.
496 size_t n = std::strlen(str);
501 #include <string.h> // C header
503 size_t n = strlen(str); // missing std namespace
506 **[back to top](#table-of-contents)**
510 Use upper case with underscores.
519 Use upper case with underscores.
521 constexpr int MY_CONSTANT = 1;
525 Use PascalCase for the enum name and upper case with underscores for the values.
535 Use PascalCase and prefix with an uppercase I. Filename has to match the interface name without the prefixed I, e.g. Logger.h
540 virtual void Log(...) = 0;
541 virtual ~ILogger() {}
546 Use PascalCase and prefix with an uppercase C. Filename has to match the class name without the prefixed C, e.g. Logger.cpp
548 class CLogger : public ILogger
551 void Log(...) override;
560 bool m_isBold{false};
565 Use PascalCase always, uppercasing the first letter even if the methods are private or protected.
566 Method parameters start with lower case and follow CamelCase style, without type prefixing (Systems Hungarian notation).
568 void MyDummyClass::DoSomething(int limitBound);
572 Variables start with lower case and follow CamelCase style. Type prefixing (Systems Hungarian notation) is discouraged.
576 bool isSunYellow{true};
581 bool bSunYellow{true}; // type prefixing
584 #### Member variables
585 Prefix non-static member variables with `m_`. Prefix static member variables with `ms_`.
588 static int ms_variableB;
591 #### Global variables
592 Prefix global variables with `g_`
594 int g_globalVariableA;
596 **WARNING:** Avoid use of globals as far as reasonably possible. We generally do not want to introduce new global variables.
598 **[back to top](#table-of-contents)**
604 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).
609 * Copyright (C) 2005-2018 Team Kodi
610 * This file is part of Kodi - https://kodi.tv
612 * SPDX-License-Identifier: GPL-2.0-or-later
613 * See LICENSES/README.md for more information.
618 // This can also continue for multiple lines:
619 // I am the second line.
630 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`).
635 * \brief Splits the given input string using the given delimiter into separate strings.
637 * If the given input string is empty, nothing will be put into the target iterator.
639 * \param destination the beginning of the destination range
640 * \param input input string to be split
641 * \param delimiter delimiter to be used to split the input string
642 * \param maxStrings (optional) maximum number of splitted strings
643 * \return output iterator to the element in the destination range one past the last element
646 template<typename OutputIt>
647 static OutputIt SplitTo(OutputIt destination, const std::string& input, const std::string& delimiter, unsigned int maxStrings = 0);
653 * @brief Function for documentation purposes (javadoc style)
657 void ReallyComplicatedFunction(); // does something really complicated
660 * \brief Frobnicate a parameter
661 * \param param parameter to frobnicate
662 * \result frobnication result
664 int Frobnicate(int param);
667 **[back to top](#table-of-contents)**
671 Use the provided logging function `CLog::Log`. Do not log to standard output or standard error using e.g. `printf` or `std::cout`.
673 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.
677 CLog::Log(LOGDEBUG, "Window size: {}x{}", width, height);
678 CLog::LogF(LOGERROR, "An error occurred in window \"{}\"", name); // Use helper function `CLog::LogF` to print also the name of method.
683 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
684 CLog::Log(LOGERROR, "{}: An error occurred in window \"{}\"", __FUNCTION__, name); // Do not use __FUNCTION__ macro, use `CLog::LogF` instead.
685 printf("Window size: %dx%d", width, height);
686 std::cout << "Window size: " << width << "x" << height << std::endl;
689 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.
693 ### 11.1. Member visibility
695 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`.
697 ### 11.2. Const correctness
699 Try to mark member functions of classes as `const` whenever reasonable.
701 ### 11.3. Overriding virtual functions
703 When overriding virtual functions of a base class, add the `override` keyword. Do not add the `virtual` keyword.
707 class CLogger : public ILogger
710 void Log(...) override;
716 class CLogger : public ILogger
719 virtual void Log(...) override;
723 ### 11.4. Default member initialization
724 Use default member initialization instead of initializer lists or constructor assignments whenever it makes sense.
728 bool m_fooBar{false};
732 ### 11.5. Destructors in interfaces
734 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)).
736 ### 11.6. Constructor Initialization Lists
738 For lines up to [line length](#line-length) everything stays on one line, excluding the braces which must be on the following lines.
741 MyClass::CMyClass(bool argOne, int argTwo) : m_argOne(argOne), m_argTwo(argTwo)
746 For longer lines, insert a line break before the colon and/or after the comma.
749 MyClass::CMyClass(bool argOne,
751 const std::string& textArg,
752 const std::shared_ptr<CMyOtherClass>& myOtherClass)
756 m_myOtherClass(myOtherClass)
761 ## 12. Other conventions
763 ### 12.1. Output parameters
764 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.
767 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.
771 char m_dataChar{...};
772 uint8_t m_dataInt = static_cast<uint8_t>(m_dataChar);
777 char m_dataChar{...};
778 uint8_t m_dataInt = (uint8_t)m_dataChar;
781 ### 12.3. `NULL` vs `nullptr`
782 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.
786 Feel free to use `auto` wherever it improves readability, without abusing it when it is not the case.
787 - Good places are iterators or types that have multiple sub-levels in a namespace.
788 - Bad places are code that expects a certain type that is not immediately clear from the context, or when you declare fundamental types.
793 constexpr float START_POINT = 5;
795 auto i = var.begin();
797 std::vector<CSizeInt> list;
798 for (const auto j : list)
807 constexpr auto START_POINT = 5; // may cause problems due to wrong type deduced, many auto variables make reading difficult
809 std::map<std::string, std::vector<int>>::iterator i = var.begin();
812 ### 12.5. `for` loops
813 Use range-based for loops wherever it makes sense. If iterators are used, see above about using `auto`.
815 for (const auto& : var)
820 Remove `const` if the value has to be modified. Do not use references to fundamental types that are not modified.
822 ### 12.6. Include guards
833 #ifndef SOME_FILE_H_INCLUDED
834 #define SOME_FILE_H_INCLUDED
839 ### 12.7. Type aliases
841 Use the C++ `using` syntax when aliasing types (encouraged when it improves readability).
845 using SizeType = int;
850 typedef int SizeType;
855 Usage of `goto` is discouraged.
859 Try to avoid using C macros. In many cases, they can be easily substituted with other non-macro constructs.
861 ### 12.10. `constexpr`
863 Prefer `constexpr` over `const` for constants when possible. Try to mark functions `constexpr` when reasonable.
865 ### 12.11. `std::string` vs `std::string_view`
867 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.
869 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.
871 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.
877 constexpr std::string_view CONSTANT_FOO{"foo-bar"};
878 } // unnamed namespace
880 void CClass::SetText(std::string_view value)
882 CLog::LogF(LOGDEBUG, "My name is {}", value);
886 SetText(CONSTANT_FOO.substr(0, 3)); // substr returns a modified view of the same string_view, thus without allocations
893 constexpr std::string CONSTANT_FOO{"foo-bar"}; // using string_view will avoid a memory allocation
894 } // unnamed namespace
896 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)
898 CLog::LogF(LOGDEBUG, "My name is {}", value);
902 SetText(CONSTANT_FOO.substr(0, 3)); // using string_view will avoid a memory allocation due to substr
905 **[back to top](#table-of-contents)**