brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 1 | # Chromium C++ style guide |
| 2 | |
| 3 | _For other languages, please see the [Chromium style guides](https://chromium.googlesource.com/chromium/src/+/master/styleguide/styleguide.md)._ |
| 4 | |
| 5 | Chromium follows the [Google C++ Style |
| 6 | Guide](https://google.github.io/styleguide/cppguide.html) unless an exception |
| 7 | is listed below. |
| 8 | |
| 9 | A checkout should give you |
| 10 | [clang-format](https://chromium.googlesource.com/chromium/src/+/master/docs/clang_format.md) |
| 11 | to automatically format C++ code. By policy, Clang's formatting of code should |
| 12 | always be accepted in code reviews. |
| 13 | |
brettw | 196290a | 2016-07-07 03:52:16 | [diff] [blame] | 14 | You can propose changes to this style guide by sending an email to |
| 15 | `[email protected]`. Ideally, the list will arrive at some consensus and you can |
| 16 | request review for a change to this file. If there's no consensus, |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 17 | `src/styleguide/c++/OWNERS` get to decide. |
| 18 | |
Tom McKee | bfea2678 | 2020-02-18 20:57:47 | [diff] [blame] | 19 | Blink code in `third_party/blink` uses [Blink style](blink-c++.md). |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 20 | |
Jeremy Roman | 1bebbea | 2019-06-20 19:17:14 | [diff] [blame] | 21 | ## Modern C++ features |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 22 | |
Jeremy Roman | 1bebbea | 2019-06-20 19:17:14 | [diff] [blame] | 23 | Some features of C++ remain forbidden, even as Chromium adopts newer versions |
| 24 | of the C++ language and standard library. These should be similar to those |
| 25 | allowed in Google style, but may occasionally differ. The status of modern C++ |
| 26 | features in Chromium is tracked in the separate |
| 27 | [C++ use in Chromium](https://chromium-cpp.appspot.com/) page. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 28 | |
| 29 | ## Naming |
| 30 | |
| 31 | * "Chromium" is the name of the project, not the product, and should never |
| 32 | appear in code, variable names, API names etc. Use "Chrome" instead. |
| 33 | |
Tommy C. Li | 1a13764a | 2018-09-17 21:18:34 | [diff] [blame] | 34 | ## Test-only Code |
| 35 | |
| 36 | * Functions used only for testing should be restricted to test-only usages |
| 37 | with the `ForTesting` suffix. This is checked at presubmit time to ensure |
| 38 | these functions are only called by test files. |
| 39 | |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 40 | ## Code formatting |
| 41 | |
| 42 | * Put `*` and `&` by the type rather than the variable name. |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 43 | * In class declarations, group function overridesĀ together within each access |
| 44 | control section, with one labeled group per parent class. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 45 | * Prefer `(foo == 0)` to `(0 == foo)`. |
| 46 | |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 47 | ## Unnamed namespaces |
| 48 | |
| 49 | Items local to a .cc file should be wrapped in an unnamed namespace. While some |
| 50 | such items are already file-scope by default in C++, not all are; also, shared |
| 51 | objects on Linux builds export all symbols, so unnamed namespaces (which |
| 52 | restrict these symbols to the compilation unit) improve function call cost and |
| 53 | reduce the size of entry point tables. |
| 54 | |
| 55 | ## Exporting symbols |
| 56 | |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 57 | Symbols can be exported (made visible outside of a shared library/DLL) by |
| 58 | annotating with a `<COMPONENT>_EXPORT` macro name (where `<COMPONENT>` is the |
| 59 | name of the component being built, e.g. BASE, NET, CONTENT, etc.). Class |
| 60 | annotations should precede the class name: |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 61 | ```c++ |
| 62 | class FOO_EXPORT Foo { |
| 63 | void Bar(); |
| 64 | void Baz(); |
| 65 | // ... |
| 66 | }; |
| 67 | ``` |
| 68 | |
| 69 | Function annotations should precede the return type: |
| 70 | ```c++ |
| 71 | class FooSingleton { |
| 72 | FOO_EXPORT Foo& GetFoo(); |
Jeremy Roman | 31220288 | 2019-02-19 21:43:50 | [diff] [blame] | 73 | FOO_EXPORT Foo& SetFooForTesting(Foo* foo); |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 74 | void SetFoo(Foo* foo); // Not exported. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 75 | }; |
| 76 | ``` |
| 77 | |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 78 | ## Multiple inheritance |
| 79 | |
| 80 | Multiple inheritance and virtual inheritance are permitted in Chromium code, |
| 81 | but discouraged (beyond the "interface" style of inheritance allowed by the |
| 82 | Google style guide, for which we do not require classes to have the "Interface" |
| 83 | suffix). Consider whether composition could solve the problem instead. |
| 84 | |
| 85 | ## Inline functions |
| 86 | |
| 87 | Simple accessors should generally be the only inline functions. These should be |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 88 | named using `snake_case()`. Virtual functions should never be declared this way. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 89 | |
| 90 | ## Logging |
| 91 | |
| 92 | Remove most logging calls before checking in. Unless you're adding temporary |
| 93 | logging to track down a specific bug, and you have a plan for how to collect |
| 94 | the logged data from user machines, you should generally not add logging |
| 95 | statements. |
| 96 | |
| 97 | For the rare case when logging needs to stay in the codebase for a while, |
| 98 | prefer `DVLOG(1)` to other logging methods. This avoids bloating the release |
| 99 | executable and in debug can be selectively enabled at runtime by command-line |
| 100 | arguments: |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 101 | * `--v=n` sets the global log level to n (default 0). All log statements with |
| 102 | a log level less than or equal to the global level will be printed. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 103 | * `--vmodule=mod=n[,mod=n,...]` overrides the global log level for the module |
| 104 | mod. Supplying the string foo for mod will affect all files named foo.cc, |
| 105 | while supplying a wildcard like `*bar/baz*` will affect all files with |
| 106 | `bar/baz` in their full pathnames. |
| 107 | |
| 108 | ## Platform-specific code |
| 109 | |
| 110 | To `#ifdef` code for specific platforms, use the macros defined in |
| 111 | `build/build_config.h` and in the Chromium build config files, not other macros |
Tommy C. Li | 1a13764a | 2018-09-17 21:18:34 | [diff] [blame] | 112 | set by specific compilers or build environments (e.g. `WIN32`). |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 113 | |
| 114 | Place platform-specific #includes in their own section below the "normal" |
| 115 | `#includes`. Repeat the standard `#include` order within this section: |
| 116 | |
| 117 | ```c++ |
| 118 | #include "foo/foo.h" |
| 119 | |
| 120 | #include <stdint.h> |
| 121 | #include <algorithm> |
| 122 | |
| 123 | #include "base/strings/utf_string_conversions.h" |
| 124 | #include "chrome/common/render_messages.h" |
| 125 | |
| 126 | #if defined(OS_WIN) |
| 127 | #include <windows.h> |
Robert Liao | c7c9a1c | 2017-10-18 01:41:31 | [diff] [blame] | 128 | #include "base/win/com_init_util.h" |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 129 | #elif defined(OS_POSIX) |
| 130 | #include "base/posix/global_descriptors.h" |
| 131 | #endif |
| 132 | ``` |
| 133 | |
| 134 | ## Types |
| 135 | |
| 136 | * Use `size_t` for object and allocation sizes, object counts, array and |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 137 | pointer offsets, vector indices, and so on. This prevents casts when |
| 138 | dealing with STL APIs, and if followed consistently across the codebase, |
| 139 | minimizes casts elsewhere. |
| 140 | * Occasionally classes may have a good reason to use a type other than |
| 141 | `size_t` for one of these concepts, e.g. as a storage space optimization. In |
| 142 | these cases, continue to use `size_t` in public-facing function |
| 143 | declarations, and continue to use unsigned types internally (e.g. |
| 144 | `uint32_t`). |
Dana Fried | 74a1889 | 2018-09-13 19:10:01 | [diff] [blame] | 145 | * Follow [Google C++ casting |
| 146 | conventions](https://google.github.io/styleguide/cppguide.html#Casting) |
| 147 | to convert arithmetic types when you know the conversion is safe. Use |
Chris Palmer | 8218b857 | 2019-02-26 00:19:16 | [diff] [blame] | 148 | `checked_cast<T>` (from `base/numerics/safe_conversions.h`) when you need to |
| 149 | `CHECK` that the source value is in range for the destination type. Use |
| 150 | `saturated_cast<T>` if you instead wish to clamp out-of-range values. |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 151 | `CheckedNumeric` is an ergonomic way to perform safe arithmetic and casting |
| 152 | in many cases. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 153 | * When passing values across network or process boundaries, use |
| 154 | explicitly-sized types for safety, since the sending and receiving ends may |
Chris Palmer | 8218b857 | 2019-02-26 00:19:16 | [diff] [blame] | 155 | not have been compiled with the same sizes for things like `int` and |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 156 | `size_t`. However, to the greatest degree possible, avoid letting these |
| 157 | sized types bleed through the APIs of the layers in question. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 158 | * Don't use `std::wstring`. Use `base::string16` or `base::FilePath` instead. |
| 159 | (Windows-specific code interfacing with system APIs using `wstring` and |
| 160 | `wchar_t` can still use `string16` and `char16`; it is safe to assume that |
| 161 | these are equivalent to the "wide" types.) |
| 162 | |
| 163 | ## Object ownership and calling conventions |
| 164 | |
| 165 | When functions need to take raw or smart pointers as parameters, use the |
| 166 | following conventions. Here we refer to the parameter type as `T` and name as |
| 167 | `t`. |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 168 | * If the function does not modify `t`'s ownership, declare the param as `T*`. |
| 169 | The caller is expected to ensure `t` stays alive as long as necessary, |
| 170 | generally through the duration of the call. Exception: In rare cases (e.g. |
| 171 | using lambdas with STL algorithms over containers of `unique_ptr<>`s), you |
| 172 | may be forced to declare the param as `const std::unique_ptr<T>&`. Do this |
| 173 | only when required. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 174 | * If the function takes ownership of a non-refcounted object, declare the |
| 175 | param as `std::unique_ptr<T>`. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 176 | * If the function (at least sometimes) takes a ref on a refcounted object, |
| 177 | declare the param as `scoped_refptr<T>`. The caller can decide |
| 178 | whether it wishes to transfer ownership (by calling `std::move(t)` when |
| 179 | passing `t`) or retain its ref (by simply passing t directly). |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 180 | * In short, functions should never take ownership of parameters passed as raw |
| 181 | pointers, and there should rarely be a need to pass smart pointers by const |
| 182 | ref. |
| 183 | |
Gabriel Charette | b62806f4a | 2019-01-29 21:08:41 | [diff] [blame] | 184 | Conventions for return values are similar with an important distinction: |
| 185 | * Return raw pointers if-and-only-if the caller does not take ownership. |
| 186 | * Return `std::unique_ptr<T>` or `scoped_refptr<T>` by value when the impl is |
| 187 | handing off ownership. |
| 188 | * **Distinction**: Return `const scoped_refptr<T>&` when the impl retains |
| 189 | ownership so the caller isn't required to take a ref: this avoids bumping |
| 190 | the reference count if the caller doesn't need ownership and also |
| 191 | [helps binary size](https://crrev.com/c/1435627)). |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 192 | |
| 193 | A great deal of Chromium code predates the above rules. In particular, some |
| 194 | functions take ownership of params passed as `T*`, or take `const |
| 195 | scoped_refptr<T>&` instead of `T*`, or return `T*` instead of |
| 196 | `scoped_refptr<T>` (to avoid refcount churn pre-C++11). Try to clean up such |
| 197 | code when you find it, or at least not make such usage any more widespread. |
| 198 | |
| 199 | ## Forward declarations vs. #includes |
| 200 | |
| 201 | Unlike the Google style guide, Chromium style prefers forward declarations to |
| 202 | `#includes` where possible. This can reduce compile times and result in fewer |
| 203 | files needing recompilation when a header changes. |
| 204 | |
| 205 | You can and should use forward declarations for most types passed or returned |
| 206 | by value, reference, or pointer, or types stored as pointer members or in most |
| 207 | STL containers. However, if it would otherwise make sense to use a type as a |
| 208 | member by-value, don't convert it to a pointer just to be able to |
| 209 | forward-declare the type. |
| 210 | |
| 211 | ## File headers |
| 212 | |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 213 | All files in Chromium start with a common license header. That header should |
| 214 | look like this: |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 215 | |
| 216 | ```c++ |
| 217 | // Copyright $YEAR The Chromium Authors. All rights reserved. |
| 218 | // Use of this source code is governed by a BSD-style license that can be |
| 219 | // found in the LICENSE file. |
| 220 | ``` |
| 221 | |
| 222 | Some important notes about this header: |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 223 | * There is no `(c)` after `Copyright`. |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 224 | * `$YEAR` should be set to the current year at the time a file is created, and |
| 225 | not changed thereafter. |
| 226 | * For files specific to Chromium OS, replace the word Chromium with the phrase |
| 227 | Chromium OS. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 228 | * If the style changes, don't bother to update existing files to comply with |
| 229 | the new style. For the same reason, don't just blindly copy an existing |
| 230 | file's header when creating a new file, since the existing file may use an |
| 231 | outdated style. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 232 | * The Chromium project hosts mirrors of some upstream open-source projects. |
| 233 | When contributing to these portions of the repository, retain the existing |
| 234 | file headers. |
| 235 | |
| 236 | Use standard `#include` guards in all header files (see the Google style guide |
| 237 | sections on these for the naming convention). Do not use `#pragma once`; |
| 238 | historically it was not supported on all platforms, and it does not seem to |
| 239 | outperform #include guards even on platforms which do support it. |
| 240 | |
| 241 | ## CHECK(), DCHECK(), and NOTREACHED() |
| 242 | |
| 243 | The `CHECK()` macro will cause an immediate crash if its condition is not met. |
| 244 | `DCHECK()` is like `CHECK()` but is only compiled in when `DCHECK_IS_ON` is true |
| 245 | (debug builds and some bot configurations, but not end-user builds). |
| 246 | `NOTREACHED()` is equivalent to `DCHECK(false)`. Here are some rules for using |
| 247 | these: |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 248 | * Use `DCHECK()` or `NOTREACHED()` as assertions, e.g. to document pre- and |
| 249 | post-conditions. A `DCHECK()` means "this condition must always be true", |
| 250 | not "this condition is normally true, but perhaps not in exceptional |
| 251 | cases." Things like disk corruption or strange network errors are examples |
| 252 | of exceptional circumstances that nevertheless should not result in |
| 253 | `DCHECK()` failure. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 254 | * A consequence of this is that you should not handle DCHECK() failures, even |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 255 | if failure would result in a crash. Attempting to handle a `DCHECK()` |
| 256 | failure is a statement that the `DCHECK()` can fail, which contradicts the |
| 257 | point of writing the `DCHECK()`. In particular, do not write code like the |
| 258 | following: |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 259 | ```c++ |
| 260 | DCHECK(foo); |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 261 | if (!foo) // Eliminate this code. |
| 262 | ... |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 263 | |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 264 | if (!bar) { // Replace this whole conditional with "DCHECK(bar);". |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 265 | NOTREACHED(); |
Peter Kasting | 5e04bd3 | 2019-05-21 21:44:10 | [diff] [blame] | 266 | return; |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 267 | } |
| 268 | ``` |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 269 | * Use `CHECK()` if the consequence of a failed assertion would be a security |
| 270 | vulnerability, where crashing the browser is preferable. Because this takes |
| 271 | down the whole browser, sometimes there are better options than `CHECK()`. |
| 272 | For example, if a renderer sends the browser process a malformed IPC, an |
| 273 | attacker may control the renderer, but we can simply kill the offending |
| 274 | renderer instead of crashing the whole browser. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 275 | * You can temporarily use `CHECK()` instead of `DCHECK()` when trying to |
| 276 | force crashes in release builds to sniff out which of your assertions is |
| 277 | failing. Don't leave these in the codebase forever; remove them or change |
| 278 | them back once you've solved the problem. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 279 | * Don't use these macros in tests, as they crash the test binary and leave |
| 280 | bots in a bad state. Use the `ASSERT_xx()` and `EXPECT_xx()` family of |
| 281 | macros, which report failures gracefully and can continue running other |
| 282 | tests. |
| 283 | |
| 284 | ## Miscellany |
| 285 | |
| 286 | * Use UTF-8 file encodings and LF line endings. |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 287 | * Unit tests and performance tests should be placed in the same directory as |
| 288 | the functionality they're testing. |
Xiaohan Wang | cc517f08 | 2019-01-16 01:58:14 | [diff] [blame] | 289 | * The [C++ Dos and Don'ts](c++-dos-and-donts.md) page has more helpful |
| 290 | information. |