blob: c405826a1e78e12101f034ebb7558dec55d03e7d [file] [log] [blame] [view]
brettwf0e606a52016-07-06 21:17:201# Chromium C++ style guide
2
Peter Kasting777e1302020-06-02 21:44:403_For other languages, please see the
John Palmerbe051302021-05-19 11:48:354[Chromium style guides](https://chromium.googlesource.com/chromium/src/+/main/styleguide/styleguide.md)._
brettwf0e606a52016-07-06 21:17:205
6Chromium follows the [Google C++ Style
7Guide](https://google.github.io/styleguide/cppguide.html) unless an exception
8is listed below.
9
10A checkout should give you
John Palmerbe051302021-05-19 11:48:3511[clang-format](https://chromium.googlesource.com/chromium/src/+/main/docs/clang_format.md)
brettwf0e606a52016-07-06 21:17:2012to automatically format C++ code. By policy, Clang's formatting of code should
13always be accepted in code reviews.
14
brettw196290a2016-07-07 03:52:1615You can propose changes to this style guide by sending an email to
16`[email protected]`. Ideally, the list will arrive at some consensus and you can
17request review for a change to this file. If there's no consensus,
brettwf0e606a52016-07-06 21:17:2018`src/styleguide/c++/OWNERS` get to decide.
19
Tom McKeebfea26782020-02-18 20:57:4720Blink code in `third_party/blink` uses [Blink style](blink-c++.md).
brettwf0e606a52016-07-06 21:17:2021
Jeremy Roman1bebbea2019-06-20 19:17:1422## Modern C++ features
brettwf0e606a52016-07-06 21:17:2023
Peter Kasting777e1302020-06-02 21:44:4024Google style
25[targets C++17](https://google.github.io/styleguide/cppguide.html#C++_Version).
Joe Mason8ae58eb32021-11-24 14:10:3826Chromium targets C++14; C++17 support is not expected before 2022. (See the
27[tracking bug](https://crbug.com/752720) for more details.) Additionally, some
28features of supported C++ versions remain forbidden. The status of Chromium's
29C++ support is covered in more detail in [Modern C++ use in Chromium](c++11.md).
brettwf0e606a52016-07-06 21:17:2030
31## Naming
32
33 * "Chromium" is the name of the project, not the product, and should never
34 appear in code, variable names, API names etc. Use "Chrome" instead.
35
Dominic Farolinof3d03072021-07-20 15:55:5436## Tests and Test-only Code
Tommy C. Li1a13764a2018-09-17 21:18:3437
38 * Functions used only for testing should be restricted to test-only usages
Peter Kasting777e1302020-06-02 21:44:4039 with the testing suffixes supported by
John Palmerbe051302021-05-19 11:48:3540 [PRESUMBIT.py](https://chromium.googlesource.com/chromium/src/+/main/PRESUBMIT.py).
Caitlin Fischer210cfab2020-05-07 20:04:3041 `ForTesting` is the conventional suffix although similar patterns, such as
42 `ForTest`, are also accepted. These suffixes are checked at presubmit time
43 to ensure the functions are called only by test files.
Roland Bock1f21a732021-05-20 16:59:5344 * Classes used only for testing should be in a GN build target that is
45 marked `testonly=true`. Tests can depend on such targets, but production
46 code can not.
Dominic Farolino200a14ec2021-07-20 16:42:4047 * While test files generally appear alongside the production code they test,
48 support code for `testonly` targets should be placed in a `test/` subdirectory.
49 For example, see `//mojo/core/core_unittest.cc` and
50 `//mojo/core/test/mojo_test_base.cc`. For test classes used across multiple
51 directories, it might make sense to move them into a nested `test` namespace for
52 clarity.
Dominic Farolinof3d03072021-07-20 15:55:5453 * Despite the Google C++ style guide
54 [deprecating](https://google.github.io/styleguide/cppguide.html#File_Names)
55 the `_unittest.cc` suffix for unit test files, in Chromium we still use this
56 suffix to distinguish unit tests from browser tests, which are written in
57 files with the `_browsertest.cc` suffix.
Tommy C. Li1a13764a2018-09-17 21:18:3458
brettwf0e606a52016-07-06 21:17:2059## Code formatting
60
61 * Put `*` and `&` by the type rather than the variable name.
danakjcd463f12021-02-12 19:53:1362 * In class declarations, group function overrides together within each access
Peter Kasting5e04bd32019-05-21 21:44:1063 control section, with one labeled group per parent class.
brettwf0e606a52016-07-06 21:17:2064 * Prefer `(foo == 0)` to `(0 == foo)`.
65
brettwf0e606a52016-07-06 21:17:2066## Unnamed namespaces
67
68Items local to a .cc file should be wrapped in an unnamed namespace. While some
69such items are already file-scope by default in C++, not all are; also, shared
70objects on Linux builds export all symbols, so unnamed namespaces (which
71restrict these symbols to the compilation unit) improve function call cost and
72reduce the size of entry point tables.
73
74## Exporting symbols
75
Peter Kasting5e04bd32019-05-21 21:44:1076Symbols can be exported (made visible outside of a shared library/DLL) by
77annotating with a `<COMPONENT>_EXPORT` macro name (where `<COMPONENT>` is the
78name of the component being built, e.g. BASE, NET, CONTENT, etc.). Class
79annotations should precede the class name:
brettwf0e606a52016-07-06 21:17:2080```c++
81class FOO_EXPORT Foo {
82 void Bar();
83 void Baz();
84 // ...
85};
86```
87
88Function annotations should precede the return type:
89```c++
90class FooSingleton {
91 FOO_EXPORT Foo& GetFoo();
Jeremy Roman312202882019-02-19 21:43:5092 FOO_EXPORT Foo& SetFooForTesting(Foo* foo);
Peter Kasting5e04bd32019-05-21 21:44:1093 void SetFoo(Foo* foo); // Not exported.
brettwf0e606a52016-07-06 21:17:2094};
95```
96
brettwf0e606a52016-07-06 21:17:2097## Multiple inheritance
98
99Multiple inheritance and virtual inheritance are permitted in Chromium code,
100but discouraged (beyond the "interface" style of inheritance allowed by the
101Google style guide, for which we do not require classes to have the "Interface"
102suffix). Consider whether composition could solve the problem instead.
103
104## Inline functions
105
106Simple accessors should generally be the only inline functions. These should be
Peter Kasting5e04bd32019-05-21 21:44:10107named using `snake_case()`. Virtual functions should never be declared this way.
brettwf0e606a52016-07-06 21:17:20108
109## Logging
110
111Remove most logging calls before checking in. Unless you're adding temporary
112logging to track down a specific bug, and you have a plan for how to collect
113the logged data from user machines, you should generally not add logging
114statements.
115
116For the rare case when logging needs to stay in the codebase for a while,
117prefer `DVLOG(1)` to other logging methods. This avoids bloating the release
118executable and in debug can be selectively enabled at runtime by command-line
119arguments:
Peter Kasting5e04bd32019-05-21 21:44:10120 * `--v=n` sets the global log level to n (default 0). All log statements with
121 a log level less than or equal to the global level will be printed.
brettwf0e606a52016-07-06 21:17:20122 * `--vmodule=mod=n[,mod=n,...]` overrides the global log level for the module
123 mod. Supplying the string foo for mod will affect all files named foo.cc,
124 while supplying a wildcard like `*bar/baz*` will affect all files with
125 `bar/baz` in their full pathnames.
126
127## Platform-specific code
128
129To `#ifdef` code for specific platforms, use the macros defined in
130`build/build_config.h` and in the Chromium build config files, not other macros
Tommy C. Li1a13764a2018-09-17 21:18:34131set by specific compilers or build environments (e.g. `WIN32`).
brettwf0e606a52016-07-06 21:17:20132
133Place platform-specific #includes in their own section below the "normal"
134`#includes`. Repeat the standard `#include` order within this section:
135
136```c++
137 #include "foo/foo.h"
138
139 #include <stdint.h>
140 #include <algorithm>
141
142 #include "base/strings/utf_string_conversions.h"
143 #include "chrome/common/render_messages.h"
144
145 #if defined(OS_WIN)
146 #include <windows.h>
Robert Liaoc7c9a1c2017-10-18 01:41:31147 #include "base/win/com_init_util.h"
brettwf0e606a52016-07-06 21:17:20148 #elif defined(OS_POSIX)
149 #include "base/posix/global_descriptors.h"
150 #endif
151```
152
153## Types
154
155 * Use `size_t` for object and allocation sizes, object counts, array and
Peter Kasting5e04bd32019-05-21 21:44:10156 pointer offsets, vector indices, and so on. This prevents casts when
157 dealing with STL APIs, and if followed consistently across the codebase,
158 minimizes casts elsewhere.
159 * Occasionally classes may have a good reason to use a type other than
160 `size_t` for one of these concepts, e.g. as a storage space optimization. In
161 these cases, continue to use `size_t` in public-facing function
162 declarations, and continue to use unsigned types internally (e.g.
163 `uint32_t`).
Dana Fried74a18892018-09-13 19:10:01164 * Follow [Google C++ casting
165 conventions](https://google.github.io/styleguide/cppguide.html#Casting)
166 to convert arithmetic types when you know the conversion is safe. Use
Chris Palmer8218b8572019-02-26 00:19:16167 `checked_cast<T>` (from `base/numerics/safe_conversions.h`) when you need to
168 `CHECK` that the source value is in range for the destination type. Use
169 `saturated_cast<T>` if you instead wish to clamp out-of-range values.
Peter Kasting5e04bd32019-05-21 21:44:10170 `CheckedNumeric` is an ergonomic way to perform safe arithmetic and casting
171 in many cases.
brettwf0e606a52016-07-06 21:17:20172 * When passing values across network or process boundaries, use
173 explicitly-sized types for safety, since the sending and receiving ends may
Chris Palmer8218b8572019-02-26 00:19:16174 not have been compiled with the same sizes for things like `int` and
brettwf0e606a52016-07-06 21:17:20175 `size_t`. However, to the greatest degree possible, avoid letting these
176 sized types bleed through the APIs of the layers in question.
Peter Kasting9e210a522021-03-20 15:45:42177 * The Google Style Guide [bans
178 UTF-16](https://google.github.io/styleguide/cppguide.html#Non-ASCII_Characters).
179 For various reasons, Chromium uses UTF-16 extensively. Use `std::u16string`
180 and `char16_t*` for 16-bit strings, `u"..."` to declare UTF-16 literals, and
181 either the actual characters or the `\uXXXX` or `\UXXXXXXXX` escapes for
182 Unicode characters. Avoid `\xXX...`-style escapes, which can cause subtle
183 problems if someone attempts to change the type of string that holds the
184 literal. In code used only on Windows, it may be necessary to use
185 `std::wstring` and `wchar_t*`; these are legal, but note that they are
186 distinct types and are often not 16-bit on other platforms.
brettwf0e606a52016-07-06 21:17:20187
188## Object ownership and calling conventions
189
190When functions need to take raw or smart pointers as parameters, use the
191following conventions. Here we refer to the parameter type as `T` and name as
192`t`.
Peter Kasting5e04bd32019-05-21 21:44:10193 * If the function does not modify `t`'s ownership, declare the param as `T*`.
194 The caller is expected to ensure `t` stays alive as long as necessary,
195 generally through the duration of the call. Exception: In rare cases (e.g.
196 using lambdas with STL algorithms over containers of `unique_ptr<>`s), you
197 may be forced to declare the param as `const std::unique_ptr<T>&`. Do this
198 only when required.
brettwf0e606a52016-07-06 21:17:20199 * If the function takes ownership of a non-refcounted object, declare the
200 param as `std::unique_ptr<T>`.
brettwf0e606a52016-07-06 21:17:20201 * If the function (at least sometimes) takes a ref on a refcounted object,
202 declare the param as `scoped_refptr<T>`. The caller can decide
203 whether it wishes to transfer ownership (by calling `std::move(t)` when
204 passing `t`) or retain its ref (by simply passing t directly).
brettwf0e606a52016-07-06 21:17:20205 * In short, functions should never take ownership of parameters passed as raw
206 pointers, and there should rarely be a need to pass smart pointers by const
207 ref.
208
Gabriel Charetteb62806f4a2019-01-29 21:08:41209Conventions for return values are similar with an important distinction:
210 * Return raw pointers if-and-only-if the caller does not take ownership.
211 * Return `std::unique_ptr<T>` or `scoped_refptr<T>` by value when the impl is
212 handing off ownership.
213 * **Distinction**: Return `const scoped_refptr<T>&` when the impl retains
214 ownership so the caller isn't required to take a ref: this avoids bumping
215 the reference count if the caller doesn't need ownership and also
216 [helps binary size](https://crrev.com/c/1435627)).
brettwf0e606a52016-07-06 21:17:20217
218A great deal of Chromium code predates the above rules. In particular, some
219functions take ownership of params passed as `T*`, or take `const
220scoped_refptr<T>&` instead of `T*`, or return `T*` instead of
221`scoped_refptr<T>` (to avoid refcount churn pre-C++11). Try to clean up such
222code when you find it, or at least not make such usage any more widespread.
223
Lukasz Anforowicz269e41d2021-11-30 18:32:01224## Non-owning pointers in class fields
225
226Use `raw_ptr<T>` for class and struct fields in place of a raw C++ pointer `T*`
227whenever possible, except in paths that include `/renderer/` or
228`blink/public/web/`. `raw_ptr<T>` is a non-owning smart pointer that has
229improved memory-safety over raw pointers, and can prevent exploitation of a
230significant percentage of Use-after-Free bugs.
231
232Using `raw_ptr<T>` may not be possible in rare cases for
233[performance reasons](../../base/memory/raw_ptr.md#Performance).
234Additionally, `raw_ptr<T>` doesn’t support some C++ scenarios (e.g. `constexpr`,
235ObjC pointers). Tooling will help to encourage use of `raw_ptr<T>`. See
236[raw_ptr.md](../../base/memory/raw_ptr.md#When-to-use-raw_ptr_T)
237for how to add exclusions.
238
brettwf0e606a52016-07-06 21:17:20239## Forward declarations vs. #includes
240
241Unlike the Google style guide, Chromium style prefers forward declarations to
242`#includes` where possible. This can reduce compile times and result in fewer
243files needing recompilation when a header changes.
244
245You can and should use forward declarations for most types passed or returned
246by value, reference, or pointer, or types stored as pointer members or in most
247STL containers. However, if it would otherwise make sense to use a type as a
248member by-value, don't convert it to a pointer just to be able to
249forward-declare the type.
250
251## File headers
252
Peter Kasting5e04bd32019-05-21 21:44:10253All files in Chromium start with a common license header. That header should
254look like this:
brettwf0e606a52016-07-06 21:17:20255
256```c++
257// Copyright $YEAR The Chromium Authors. All rights reserved.
258// Use of this source code is governed by a BSD-style license that can be
259// found in the LICENSE file.
260```
261
262Some important notes about this header:
brettwf0e606a52016-07-06 21:17:20263 * There is no `(c)` after `Copyright`.
Peter Kasting5e04bd32019-05-21 21:44:10264 * `$YEAR` should be set to the current year at the time a file is created, and
265 not changed thereafter.
266 * For files specific to Chromium OS, replace the word Chromium with the phrase
267 Chromium OS.
brettwf0e606a52016-07-06 21:17:20268 * If the style changes, don't bother to update existing files to comply with
269 the new style. For the same reason, don't just blindly copy an existing
270 file's header when creating a new file, since the existing file may use an
271 outdated style.
brettwf0e606a52016-07-06 21:17:20272 * The Chromium project hosts mirrors of some upstream open-source projects.
273 When contributing to these portions of the repository, retain the existing
274 file headers.
275
276Use standard `#include` guards in all header files (see the Google style guide
277sections on these for the naming convention). Do not use `#pragma once`;
278historically it was not supported on all platforms, and it does not seem to
279outperform #include guards even on platforms which do support it.
280
281## CHECK(), DCHECK(), and NOTREACHED()
282
283The `CHECK()` macro will cause an immediate crash if its condition is not met.
284`DCHECK()` is like `CHECK()` but is only compiled in when `DCHECK_IS_ON` is true
285(debug builds and some bot configurations, but not end-user builds).
286`NOTREACHED()` is equivalent to `DCHECK(false)`. Here are some rules for using
287these:
brettwf0e606a52016-07-06 21:17:20288 * Use `DCHECK()` or `NOTREACHED()` as assertions, e.g. to document pre- and
289 post-conditions. A `DCHECK()` means "this condition must always be true",
290 not "this condition is normally true, but perhaps not in exceptional
291 cases." Things like disk corruption or strange network errors are examples
292 of exceptional circumstances that nevertheless should not result in
293 `DCHECK()` failure.
brettwf0e606a52016-07-06 21:17:20294 * A consequence of this is that you should not handle DCHECK() failures, even
Peter Kasting5e04bd32019-05-21 21:44:10295 if failure would result in a crash. Attempting to handle a `DCHECK()`
296 failure is a statement that the `DCHECK()` can fail, which contradicts the
297 point of writing the `DCHECK()`. In particular, do not write code like the
298 following:
brettwf0e606a52016-07-06 21:17:20299 ```c++
300 DCHECK(foo);
Peter Kasting5e04bd32019-05-21 21:44:10301 if (!foo) // Eliminate this code.
302 ...
brettwf0e606a52016-07-06 21:17:20303
Peter Kasting5e04bd32019-05-21 21:44:10304 if (!bar) { // Replace this whole conditional with "DCHECK(bar);".
brettwf0e606a52016-07-06 21:17:20305 NOTREACHED();
Peter Kasting5e04bd32019-05-21 21:44:10306 return;
brettwf0e606a52016-07-06 21:17:20307 }
308 ```
brettwf0e606a52016-07-06 21:17:20309 * Use `CHECK()` if the consequence of a failed assertion would be a security
310 vulnerability, where crashing the browser is preferable. Because this takes
311 down the whole browser, sometimes there are better options than `CHECK()`.
312 For example, if a renderer sends the browser process a malformed IPC, an
313 attacker may control the renderer, but we can simply kill the offending
314 renderer instead of crashing the whole browser.
brettwf0e606a52016-07-06 21:17:20315 * You can temporarily use `CHECK()` instead of `DCHECK()` when trying to
316 force crashes in release builds to sniff out which of your assertions is
317 failing. Don't leave these in the codebase forever; remove them or change
318 them back once you've solved the problem.
brettwf0e606a52016-07-06 21:17:20319 * Don't use these macros in tests, as they crash the test binary and leave
320 bots in a bad state. Use the `ASSERT_xx()` and `EXPECT_xx()` family of
321 macros, which report failures gracefully and can continue running other
322 tests.
danakjcd463f12021-02-12 19:53:13323 * Dereferencing a null pointer in C++ is generally UB (undefined behavior) as
324 the compiler is free to assume a dereference means the pointer is not null
325 and may apply optimizations based on that. As such, there is sometimes a
326 strong opinion to `CHECK()` pointers before dereference. Chromium builds
327 with the `no-delete-null-pointer-checks` Clang/GCC flag which prevents such
328 optimizations, meaning the side effect of a null dereference would just be
329 the use of 0x0 which will lead to a crash on all the platforms Chromium
330 supports. As such we do not use `CHECK()` to guard pointer deferences. A
331 `DCHECK()` can be used to document that a pointer is never null, and doing
332 so as early as possible can help with debugging, though our styleguide now
333 recommends using a reference instead of a pointer when it cannot be null.
brettwf0e606a52016-07-06 21:17:20334
335## Miscellany
336
337 * Use UTF-8 file encodings and LF line endings.
brettwf0e606a52016-07-06 21:17:20338 * Unit tests and performance tests should be placed in the same directory as
339 the functionality they're testing.
Xiaohan Wangcc517f082019-01-16 01:58:14340 * The [C++ Dos and Don'ts](c++-dos-and-donts.md) page has more helpful
341 information.