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 | |
Daniel Cheng | 7ecc1d6 | 2017-06-12 20:24:30 | [diff] [blame] | 19 | Blink code in `third_party/WebKit` uses [Blink style](blink-c++.md). |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 20 | |
| 21 | ## C++11 features |
| 22 | |
| 23 | Google style has adopted most C++11 features, but Chromium has a more |
| 24 | restricted set. The status of C++11 features in Chromium is tracked in the |
| 25 | separate [C++11 use in Chromium](https://chromium-cpp.appspot.com/) page. |
| 26 | |
| 27 | ## Naming |
| 28 | |
| 29 | * "Chromium" is the name of the project, not the product, and should never |
| 30 | appear in code, variable names, API names etc. Use "Chrome" instead. |
| 31 | |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 32 | * Functions used only for testing should be restricted to test-only scenarios |
| 33 | either by `#ifdefing` them appropriately (e.g. `#if defined(UNIT_TEST)`) or |
| 34 | by naming them with a `ForTesting` suffix. The latter will be checked at |
| 35 | presubmit time to ensure they're only called by test files. |
| 36 | |
| 37 | ## Code formatting |
| 38 | |
| 39 | * Put `*` and `&` by the type rather than the variable name. |
| 40 | |
| 41 | * When you derive from a base class, group any overriding functions in your |
| 42 | header file in one labeled section. Use the override specifier on all these |
| 43 | functions. |
| 44 | |
| 45 | * Prefer `(foo == 0)` to `(0 == foo)`. |
| 46 | |
| 47 | * Function declaration order should match function definition order. |
| 48 | |
| 49 | * Prefer putting delegate classes in their own header files. Implementors of |
| 50 | the delegate interface will often be included elsewhere, which will often |
| 51 | cause more coupling with the header of the main class. |
| 52 | |
| 53 | * Don't use else after return. So use: |
| 54 | ```c++ |
| 55 | if (foo) |
| 56 | return 1; |
| 57 | return 2; |
| 58 | ``` |
| 59 | instead of: |
| 60 | ```c++ |
| 61 | if (foo) |
| 62 | return 1; |
| 63 | else |
| 64 | return 2; |
| 65 | ``` |
| 66 | |
| 67 | ## Unnamed namespaces |
| 68 | |
| 69 | Items local to a .cc file should be wrapped in an unnamed namespace. While some |
| 70 | such items are already file-scope by default in C++, not all are; also, shared |
| 71 | objects on Linux builds export all symbols, so unnamed namespaces (which |
| 72 | restrict these symbols to the compilation unit) improve function call cost and |
| 73 | reduce the size of entry point tables. |
| 74 | |
| 75 | ## Exporting symbols |
| 76 | |
| 77 | When building shared libraries and DLLs, we need to indicate which functions |
| 78 | and classes should be visible outside of the library, and which should only be |
| 79 | visible inside the library. |
| 80 | |
| 81 | Symbols can be exported by annotating with a `<COMPONENT>_EXPORT` macro name |
| 82 | (where `<COMPONENT>` is the name of the component being built, e.g. BASE, NET, |
| 83 | CONTENT, etc.). Class annotations should precede the class name: |
| 84 | ```c++ |
| 85 | class FOO_EXPORT Foo { |
| 86 | void Bar(); |
| 87 | void Baz(); |
| 88 | // ... |
| 89 | }; |
| 90 | ``` |
| 91 | |
| 92 | Function annotations should precede the return type: |
| 93 | ```c++ |
| 94 | class FooSingleton { |
| 95 | FOO_EXPORT Foo& GetFoo(); |
| 96 | FOO_EXPORT Foo& SetFooForTesting(Foo& foo); |
| 97 | void SetFoo(Foo& foo); |
| 98 | }; |
| 99 | ``` |
| 100 | |
| 101 | These examples result in `Foo::Bar()`, `Foo::Baz()`, `FooSingleton::GetFoo()`, |
| 102 | and `FooSingleton::SetFooForTesting()` all being available outside of the DLL, |
| 103 | but not `FooSingleton::SetFoo()`. |
| 104 | |
| 105 | Whether something is exported is distinct from whether it is public or private, |
| 106 | or even whether it would normally be considered part of the external API. For |
| 107 | example, if part of the external API is an inlined function that calls a |
| 108 | private function, that private function must be exported as well. |
| 109 | |
| 110 | ## Multiple inheritance |
| 111 | |
| 112 | Multiple inheritance and virtual inheritance are permitted in Chromium code, |
| 113 | but discouraged (beyond the "interface" style of inheritance allowed by the |
| 114 | Google style guide, for which we do not require classes to have the "Interface" |
| 115 | suffix). Consider whether composition could solve the problem instead. |
| 116 | |
| 117 | ## Inline functions |
| 118 | |
| 119 | Simple accessors should generally be the only inline functions. These should be |
| 120 | named `unix_hacker_style()`. Virtual functions should never be declared this way. |
| 121 | For more detail, consult the [C++ Dos and |
| 122 | Don'ts](https://www.chromium.org/developers/coding-style/cpp-dos-and-donts) |
| 123 | section on inlining. |
| 124 | |
| 125 | ## Logging |
| 126 | |
| 127 | Remove most logging calls before checking in. Unless you're adding temporary |
| 128 | logging to track down a specific bug, and you have a plan for how to collect |
| 129 | the logged data from user machines, you should generally not add logging |
| 130 | statements. |
| 131 | |
| 132 | For the rare case when logging needs to stay in the codebase for a while, |
| 133 | prefer `DVLOG(1)` to other logging methods. This avoids bloating the release |
| 134 | executable and in debug can be selectively enabled at runtime by command-line |
| 135 | arguments: |
| 136 | |
| 137 | * `--v=n` sets the global log level to n (default 0). All log statements with a |
| 138 | log level less than or equal to the global level will be printed. |
| 139 | |
| 140 | * `--vmodule=mod=n[,mod=n,...]` overrides the global log level for the module |
| 141 | mod. Supplying the string foo for mod will affect all files named foo.cc, |
| 142 | while supplying a wildcard like `*bar/baz*` will affect all files with |
| 143 | `bar/baz` in their full pathnames. |
| 144 | |
| 145 | ## Platform-specific code |
| 146 | |
| 147 | To `#ifdef` code for specific platforms, use the macros defined in |
| 148 | `build/build_config.h` and in the Chromium build config files, not other macros |
| 149 | set by specific compilers or build environments (e.g. `WIN32`). |
| 150 | |
| 151 | Place platform-specific #includes in their own section below the "normal" |
| 152 | `#includes`. Repeat the standard `#include` order within this section: |
| 153 | |
| 154 | ```c++ |
| 155 | #include "foo/foo.h" |
| 156 | |
| 157 | #include <stdint.h> |
| 158 | #include <algorithm> |
| 159 | |
| 160 | #include "base/strings/utf_string_conversions.h" |
| 161 | #include "chrome/common/render_messages.h" |
| 162 | |
| 163 | #if defined(OS_WIN) |
| 164 | #include <windows.h> |
| 165 | #include "base/win/scoped_comptr.h" |
| 166 | #elif defined(OS_POSIX) |
| 167 | #include "base/posix/global_descriptors.h" |
| 168 | #endif |
| 169 | ``` |
| 170 | |
| 171 | ## Types |
| 172 | |
| 173 | * Use `size_t` for object and allocation sizes, object counts, array and |
| 174 | pointer offsets, vector indices, and so on. The signed types are incorrect |
| 175 | and unsafe for these purposes (e.g. integer overflow behavior for signed |
| 176 | types is undefined in the C and C++ standards, while the behavior is |
| 177 | defined for unsigned types.) The C++ STL is a guide here: they use `size_t` |
| 178 | and `foo::size_type` for very good reasons. |
| 179 | |
| 180 | * Use `size_t` directly in preference to `std::string::size_type` and similar. |
| 181 | |
| 182 | * Occasionally classes may have a good reason to use a type other than `size_t` |
| 183 | for one of these concepts, e.g. as a storage space optimization. In these |
| 184 | cases, continue to use `size_t` in public-facing function declarations. |
| 185 | |
| 186 | * Be aware that `size_t` (object sizes and indices), `off_t` (file offsets), |
| 187 | `ptrdiff_t` (the difference between two pointer values), `intptr_t` (an |
| 188 | integer type large enough to hold the value of a pointer), `uint32_t`, |
| 189 | `uint64_t`, and so on are not necessarily the same. Use the right type for |
| 190 | your purpose. |
| 191 | |
| 192 | * When casting to and from different types, use `static_cast<>()` when you know |
| 193 | the conversion is safe. Use `checked_cast<>()` (from |
| 194 | `base/numerics/safe_conversions.h`) when you need to enforce via `CHECK()` that |
| 195 | the source value is in-range for the destination type. Use |
| 196 | `saturated_cast<>()` (from the same file) if you instead wish to clamp |
| 197 | out-of-range values. |
| 198 | |
| 199 | * Do not use unsigned types to mean "this value should never be < 0". For |
| 200 | that, use assertions or run-time checks (as appropriate). |
| 201 | |
| 202 | * In cases where the exact size of the type matters (e.g. a 32-bit pixel |
| 203 | value, a bitmask, or a counter that has to be a particular width), use one |
| 204 | of the sized types from `<stdint.h>`, e.g. `uint32_t`. |
| 205 | |
| 206 | * When passing values across network or process boundaries, use |
| 207 | explicitly-sized types for safety, since the sending and receiving ends may |
| 208 | not have been compiled with the same sizes for things like int and |
| 209 | `size_t`. However, to the greatest degree possible, avoid letting these |
| 210 | sized types bleed through the APIs of the layers in question. |
| 211 | |
| 212 | * Don't use `std::wstring`. Use `base::string16` or `base::FilePath` instead. |
| 213 | (Windows-specific code interfacing with system APIs using `wstring` and |
| 214 | `wchar_t` can still use `string16` and `char16`; it is safe to assume that |
| 215 | these are equivalent to the "wide" types.) |
| 216 | |
| 217 | ## Object ownership and calling conventions |
| 218 | |
| 219 | When functions need to take raw or smart pointers as parameters, use the |
| 220 | following conventions. Here we refer to the parameter type as `T` and name as |
| 221 | `t`. |
| 222 | |
| 223 | * If the function does not modify `t`'s ownership, declare the param as `T*`. The |
| 224 | caller is expected to ensure `t` stays alive as long as necessary, generally |
| 225 | through the duration of the call. Exception: In rare cases (e.g. using |
claudiomagni | e85f90c | 2017-05-10 05:40:29 | [diff] [blame] | 226 | lambdas with STL algorithms over containers of `unique_ptr<>`s), you may be |
brettw | f0e606a5 | 2016-07-06 21:17:20 | [diff] [blame] | 227 | forced to declare the param as `const std::unique_ptr<T>&`. Do this only when |
| 228 | required. |
| 229 | |
| 230 | * If the function takes ownership of a non-refcounted object, declare the |
| 231 | param as `std::unique_ptr<T>`. |
| 232 | |
| 233 | * If the function (at least sometimes) takes a ref on a refcounted object, |
| 234 | declare the param as `scoped_refptr<T>`. The caller can decide |
| 235 | whether it wishes to transfer ownership (by calling `std::move(t)` when |
| 236 | passing `t`) or retain its ref (by simply passing t directly). |
| 237 | |
| 238 | * In short, functions should never take ownership of parameters passed as raw |
| 239 | pointers, and there should rarely be a need to pass smart pointers by const |
| 240 | ref. |
| 241 | |
| 242 | Conventions for return values are similar: return raw pointers when the caller |
| 243 | does not take ownership, and return smart pointers by value otherwise, |
| 244 | potentially in conjunction with `std::move()`. |
| 245 | |
| 246 | A great deal of Chromium code predates the above rules. In particular, some |
| 247 | functions take ownership of params passed as `T*`, or take `const |
| 248 | scoped_refptr<T>&` instead of `T*`, or return `T*` instead of |
| 249 | `scoped_refptr<T>` (to avoid refcount churn pre-C++11). Try to clean up such |
| 250 | code when you find it, or at least not make such usage any more widespread. |
| 251 | |
| 252 | ## Forward declarations vs. #includes |
| 253 | |
| 254 | Unlike the Google style guide, Chromium style prefers forward declarations to |
| 255 | `#includes` where possible. This can reduce compile times and result in fewer |
| 256 | files needing recompilation when a header changes. |
| 257 | |
| 258 | You can and should use forward declarations for most types passed or returned |
| 259 | by value, reference, or pointer, or types stored as pointer members or in most |
| 260 | STL containers. However, if it would otherwise make sense to use a type as a |
| 261 | member by-value, don't convert it to a pointer just to be able to |
| 262 | forward-declare the type. |
| 263 | |
| 264 | ## File headers |
| 265 | |
| 266 | All files in Chromium start with a common license header. That header should look like this: |
| 267 | |
| 268 | ```c++ |
| 269 | // Copyright $YEAR The Chromium Authors. All rights reserved. |
| 270 | // Use of this source code is governed by a BSD-style license that can be |
| 271 | // found in the LICENSE file. |
| 272 | ``` |
| 273 | |
| 274 | Some important notes about this header: |
| 275 | |
| 276 | * There is no `(c)` after `Copyright`. |
| 277 | |
| 278 | * `$YEAR` should be set to the current year at the time a file is created, and not changed thereafter. |
| 279 | |
| 280 | * For files specific to Chromium OS, replace the word Chromium with the phrase Chromium OS. |
| 281 | |
| 282 | * If the style changes, don't bother to update existing files to comply with |
| 283 | the new style. For the same reason, don't just blindly copy an existing |
| 284 | file's header when creating a new file, since the existing file may use an |
| 285 | outdated style. |
| 286 | |
| 287 | * The Chromium project hosts mirrors of some upstream open-source projects. |
| 288 | When contributing to these portions of the repository, retain the existing |
| 289 | file headers. |
| 290 | |
| 291 | Use standard `#include` guards in all header files (see the Google style guide |
| 292 | sections on these for the naming convention). Do not use `#pragma once`; |
| 293 | historically it was not supported on all platforms, and it does not seem to |
| 294 | outperform #include guards even on platforms which do support it. |
| 295 | |
| 296 | ## CHECK(), DCHECK(), and NOTREACHED() |
| 297 | |
| 298 | The `CHECK()` macro will cause an immediate crash if its condition is not met. |
| 299 | `DCHECK()` is like `CHECK()` but is only compiled in when `DCHECK_IS_ON` is true |
| 300 | (debug builds and some bot configurations, but not end-user builds). |
| 301 | `NOTREACHED()` is equivalent to `DCHECK(false)`. Here are some rules for using |
| 302 | these: |
| 303 | |
| 304 | * Use `DCHECK()` or `NOTREACHED()` as assertions, e.g. to document pre- and |
| 305 | post-conditions. A `DCHECK()` means "this condition must always be true", |
| 306 | not "this condition is normally true, but perhaps not in exceptional |
| 307 | cases." Things like disk corruption or strange network errors are examples |
| 308 | of exceptional circumstances that nevertheless should not result in |
| 309 | `DCHECK()` failure. |
| 310 | |
| 311 | * A consequence of this is that you should not handle DCHECK() failures, even |
| 312 | if failure would result in a crash. Attempting to handle a `DCHECK()` failure |
| 313 | is a statement that the `DCHECK()` can fail, which contradicts the point of |
| 314 | writing the `DCHECK()`. In particular, do not write code like the following: |
| 315 | ```c++ |
| 316 | DCHECK(foo); |
| 317 | if (!foo) ... // Can't succeed! |
| 318 | |
| 319 | if (!bar) { |
| 320 | NOTREACHED(); |
| 321 | return; // Replace this whole conditional with "DCHECK(bar);" and keep going instead. |
| 322 | } |
| 323 | ``` |
| 324 | |
| 325 | * Use `CHECK()` if the consequence of a failed assertion would be a security |
| 326 | vulnerability, where crashing the browser is preferable. Because this takes |
| 327 | down the whole browser, sometimes there are better options than `CHECK()`. |
| 328 | For example, if a renderer sends the browser process a malformed IPC, an |
| 329 | attacker may control the renderer, but we can simply kill the offending |
| 330 | renderer instead of crashing the whole browser. |
| 331 | |
| 332 | * You can temporarily use `CHECK()` instead of `DCHECK()` when trying to |
| 333 | force crashes in release builds to sniff out which of your assertions is |
| 334 | failing. Don't leave these in the codebase forever; remove them or change |
| 335 | them back once you've solved the problem. |
| 336 | |
| 337 | * Don't use these macros in tests, as they crash the test binary and leave |
| 338 | bots in a bad state. Use the `ASSERT_xx()` and `EXPECT_xx()` family of |
| 339 | macros, which report failures gracefully and can continue running other |
| 340 | tests. |
| 341 | |
| 342 | ## Miscellany |
| 343 | |
| 344 | * Use UTF-8 file encodings and LF line endings. |
| 345 | |
| 346 | * Unit tests and performance tests should be placed in the same directory as |
| 347 | the functionality they're testing. |
| 348 | |
| 349 | * The [C++ do's and |
| 350 | don'ts](https://sites.google.com/a/chromium.org/dev/developers/coding-style/cpp-dos-and-donts) |
| 351 | page has more helpful information. |