blob: 5fec3c4349d747da04dc81c78d5257a08af98b46 [file] [log] [blame] [view]
brettwf0e606a52016-07-06 21:17:201# 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
5Chromium follows the [Google C++ Style
6Guide](https://google.github.io/styleguide/cppguide.html) unless an exception
7is listed below.
8
9A checkout should give you
10[clang-format](https://chromium.googlesource.com/chromium/src/+/master/docs/clang_format.md)
11to automatically format C++ code. By policy, Clang's formatting of code should
12always be accepted in code reviews.
13
brettw196290a2016-07-07 03:52:1614You 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
16request review for a change to this file. If there's no consensus,
brettwf0e606a52016-07-06 21:17:2017`src/styleguide/c++/OWNERS` get to decide.
18
Tom McKeebfea26782020-02-18 20:57:4719Blink code in `third_party/blink` uses [Blink style](blink-c++.md).
brettwf0e606a52016-07-06 21:17:2020
Jeremy Roman1bebbea2019-06-20 19:17:1421## Modern C++ features
brettwf0e606a52016-07-06 21:17:2022
Jeremy Roman1bebbea2019-06-20 19:17:1423Some features of C++ remain forbidden, even as Chromium adopts newer versions
24of the C++ language and standard library. These should be similar to those
25allowed in Google style, but may occasionally differ. The status of modern C++
26features in Chromium is tracked in the separate
27[C++ use in Chromium](https://chromium-cpp.appspot.com/) page.
brettwf0e606a52016-07-06 21:17:2028
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. Li1a13764a2018-09-17 21:18:3434## 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
brettwf0e606a52016-07-06 21:17:2040## Code formatting
41
42 * Put `*` and `&` by the type rather than the variable name.
Peter Kasting5e04bd32019-05-21 21:44:1043 * In class declarations, group function overridesĀ together within each access
44 control section, with one labeled group per parent class.
brettwf0e606a52016-07-06 21:17:2045 * Prefer `(foo == 0)` to `(0 == foo)`.
46
brettwf0e606a52016-07-06 21:17:2047## Unnamed namespaces
48
49Items local to a .cc file should be wrapped in an unnamed namespace. While some
50such items are already file-scope by default in C++, not all are; also, shared
51objects on Linux builds export all symbols, so unnamed namespaces (which
52restrict these symbols to the compilation unit) improve function call cost and
53reduce the size of entry point tables.
54
55## Exporting symbols
56
Peter Kasting5e04bd32019-05-21 21:44:1057Symbols can be exported (made visible outside of a shared library/DLL) by
58annotating with a `<COMPONENT>_EXPORT` macro name (where `<COMPONENT>` is the
59name of the component being built, e.g. BASE, NET, CONTENT, etc.). Class
60annotations should precede the class name:
brettwf0e606a52016-07-06 21:17:2061```c++
62class FOO_EXPORT Foo {
63 void Bar();
64 void Baz();
65 // ...
66};
67```
68
69Function annotations should precede the return type:
70```c++
71class FooSingleton {
72 FOO_EXPORT Foo& GetFoo();
Jeremy Roman312202882019-02-19 21:43:5073 FOO_EXPORT Foo& SetFooForTesting(Foo* foo);
Peter Kasting5e04bd32019-05-21 21:44:1074 void SetFoo(Foo* foo); // Not exported.
brettwf0e606a52016-07-06 21:17:2075};
76```
77
brettwf0e606a52016-07-06 21:17:2078## Multiple inheritance
79
80Multiple inheritance and virtual inheritance are permitted in Chromium code,
81but discouraged (beyond the "interface" style of inheritance allowed by the
82Google style guide, for which we do not require classes to have the "Interface"
83suffix). Consider whether composition could solve the problem instead.
84
85## Inline functions
86
87Simple accessors should generally be the only inline functions. These should be
Peter Kasting5e04bd32019-05-21 21:44:1088named using `snake_case()`. Virtual functions should never be declared this way.
brettwf0e606a52016-07-06 21:17:2089
90## Logging
91
92Remove most logging calls before checking in. Unless you're adding temporary
93logging to track down a specific bug, and you have a plan for how to collect
94the logged data from user machines, you should generally not add logging
95statements.
96
97For the rare case when logging needs to stay in the codebase for a while,
98prefer `DVLOG(1)` to other logging methods. This avoids bloating the release
99executable and in debug can be selectively enabled at runtime by command-line
100arguments:
Peter Kasting5e04bd32019-05-21 21:44:10101 * `--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.
brettwf0e606a52016-07-06 21:17:20103 * `--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
110To `#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. Li1a13764a2018-09-17 21:18:34112set by specific compilers or build environments (e.g. `WIN32`).
brettwf0e606a52016-07-06 21:17:20113
114Place 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 Liaoc7c9a1c2017-10-18 01:41:31128 #include "base/win/com_init_util.h"
brettwf0e606a52016-07-06 21:17:20129 #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 Kasting5e04bd32019-05-21 21:44:10137 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 Fried74a18892018-09-13 19:10:01145 * 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 Palmer8218b8572019-02-26 00:19:16148 `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 Kasting5e04bd32019-05-21 21:44:10151 `CheckedNumeric` is an ergonomic way to perform safe arithmetic and casting
152 in many cases.
brettwf0e606a52016-07-06 21:17:20153 * When passing values across network or process boundaries, use
154 explicitly-sized types for safety, since the sending and receiving ends may
Chris Palmer8218b8572019-02-26 00:19:16155 not have been compiled with the same sizes for things like `int` and
brettwf0e606a52016-07-06 21:17:20156 `size_t`. However, to the greatest degree possible, avoid letting these
157 sized types bleed through the APIs of the layers in question.
brettwf0e606a52016-07-06 21:17:20158 * 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
165When functions need to take raw or smart pointers as parameters, use the
166following conventions. Here we refer to the parameter type as `T` and name as
167`t`.
Peter Kasting5e04bd32019-05-21 21:44:10168 * 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.
brettwf0e606a52016-07-06 21:17:20174 * If the function takes ownership of a non-refcounted object, declare the
175 param as `std::unique_ptr<T>`.
brettwf0e606a52016-07-06 21:17:20176 * 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).
brettwf0e606a52016-07-06 21:17:20180 * 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 Charetteb62806f4a2019-01-29 21:08:41184Conventions 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)).
brettwf0e606a52016-07-06 21:17:20192
193A great deal of Chromium code predates the above rules. In particular, some
194functions take ownership of params passed as `T*`, or take `const
195scoped_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
197code when you find it, or at least not make such usage any more widespread.
198
199## Forward declarations vs. #includes
200
201Unlike the Google style guide, Chromium style prefers forward declarations to
202`#includes` where possible. This can reduce compile times and result in fewer
203files needing recompilation when a header changes.
204
205You can and should use forward declarations for most types passed or returned
206by value, reference, or pointer, or types stored as pointer members or in most
207STL containers. However, if it would otherwise make sense to use a type as a
208member by-value, don't convert it to a pointer just to be able to
209forward-declare the type.
210
211## File headers
212
Peter Kasting5e04bd32019-05-21 21:44:10213All files in Chromium start with a common license header. That header should
214look like this:
brettwf0e606a52016-07-06 21:17:20215
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
222Some important notes about this header:
brettwf0e606a52016-07-06 21:17:20223 * There is no `(c)` after `Copyright`.
Peter Kasting5e04bd32019-05-21 21:44:10224 * `$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.
brettwf0e606a52016-07-06 21:17:20228 * 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.
brettwf0e606a52016-07-06 21:17:20232 * 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
236Use standard `#include` guards in all header files (see the Google style guide
237sections on these for the naming convention). Do not use `#pragma once`;
238historically it was not supported on all platforms, and it does not seem to
239outperform #include guards even on platforms which do support it.
240
241## CHECK(), DCHECK(), and NOTREACHED()
242
243The `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
247these:
brettwf0e606a52016-07-06 21:17:20248 * 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.
brettwf0e606a52016-07-06 21:17:20254 * A consequence of this is that you should not handle DCHECK() failures, even
Peter Kasting5e04bd32019-05-21 21:44:10255 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:
brettwf0e606a52016-07-06 21:17:20259 ```c++
260 DCHECK(foo);
Peter Kasting5e04bd32019-05-21 21:44:10261 if (!foo) // Eliminate this code.
262 ...
brettwf0e606a52016-07-06 21:17:20263
Peter Kasting5e04bd32019-05-21 21:44:10264 if (!bar) { // Replace this whole conditional with "DCHECK(bar);".
brettwf0e606a52016-07-06 21:17:20265 NOTREACHED();
Peter Kasting5e04bd32019-05-21 21:44:10266 return;
brettwf0e606a52016-07-06 21:17:20267 }
268 ```
brettwf0e606a52016-07-06 21:17:20269 * 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.
brettwf0e606a52016-07-06 21:17:20275 * 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.
brettwf0e606a52016-07-06 21:17:20279 * 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.
brettwf0e606a52016-07-06 21:17:20287 * Unit tests and performance tests should be placed in the same directory as
288 the functionality they're testing.
Xiaohan Wangcc517f082019-01-16 01:58:14289 * The [C++ Dos and Don'ts](c++-dos-and-donts.md) page has more helpful
290 information.