blob: 5f55772a25e58a98f3dd92b22534e25deed6becc [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 Kasting1865f2772021-12-23 21:23:5824Google and Chromium style
Jan Wilken Dörrie276003c2023-11-27 16:59:5725[targets C++20](https://google.github.io/styleguide/cppguide.html#C++_Version).
Peter Kasting1865f2772021-12-23 21:23:5826Additionally, some features of supported C++ versions remain forbidden. The
27status of Chromium's C++ support is covered in more detail in
Avi Drissman0aafa9e2022-01-18 21:41:0128[Modern C++ use in Chromium](c++-features.md).
brettwf0e606a52016-07-06 21:17:2029
30## Naming
31
32 * "Chromium" is the name of the project, not the product, and should never
33 appear in code, variable names, API names etc. Use "Chrome" instead.
34
Dominic Farolinof3d03072021-07-20 15:55:5435## Tests and Test-only Code
Tommy C. Li1a13764a2018-09-17 21:18:3436
37 * Functions used only for testing should be restricted to test-only usages
Peter Kasting777e1302020-06-02 21:44:4038 with the testing suffixes supported by
Joseph Koshy0b38a3242022-07-13 15:01:4039 [PRESUBMIT.py](https://chromium.googlesource.com/chromium/src/+/main/PRESUBMIT.py).
Caitlin Fischer210cfab2020-05-07 20:04:3040 `ForTesting` is the conventional suffix although similar patterns, such as
41 `ForTest`, are also accepted. These suffixes are checked at presubmit time
Sam Fortiner3b827bd2023-11-27 21:42:0142 to ensure the functions are called only by test files. In the rare case of
43 adding a test-only code path to an area where a testing suffix is not
44 possible, CHECK_IS_TEST() may be appropriate.
Roland Bock1f21a732021-05-20 16:59:5345 * Classes used only for testing should be in a GN build target that is
46 marked `testonly=true`. Tests can depend on such targets, but production
47 code can not.
Dominic Farolino200a14ec2021-07-20 16:42:4048 * While test files generally appear alongside the production code they test,
49 support code for `testonly` targets should be placed in a `test/` subdirectory.
50 For example, see `//mojo/core/core_unittest.cc` and
51 `//mojo/core/test/mojo_test_base.cc`. For test classes used across multiple
52 directories, it might make sense to move them into a nested `test` namespace for
53 clarity.
Dominic Farolinof3d03072021-07-20 15:55:5454 * Despite the Google C++ style guide
55 [deprecating](https://google.github.io/styleguide/cppguide.html#File_Names)
56 the `_unittest.cc` suffix for unit test files, in Chromium we still use this
57 suffix to distinguish unit tests from browser tests, which are written in
58 files with the `_browsertest.cc` suffix.
Tommy C. Li1a13764a2018-09-17 21:18:3459
brettwf0e606a52016-07-06 21:17:2060## Code formatting
61
62 * Put `*` and `&` by the type rather than the variable name.
danakjcd463f12021-02-12 19:53:1363 * In class declarations, group function overrides together within each access
Peter Kasting5e04bd32019-05-21 21:44:1064 control section, with one labeled group per parent class.
brettwf0e606a52016-07-06 21:17:2065 * Prefer `(foo == 0)` to `(0 == foo)`.
Nicholas Bishop27098a12024-01-16 20:41:5566 * Use `{}` on all conditionals/loops.
brettwf0e606a52016-07-06 21:17:2067
brettwf0e606a52016-07-06 21:17:2068## Unnamed namespaces
69
70Items local to a .cc file should be wrapped in an unnamed namespace. While some
71such items are already file-scope by default in C++, not all are; also, shared
72objects on Linux builds export all symbols, so unnamed namespaces (which
73restrict these symbols to the compilation unit) improve function call cost and
74reduce the size of entry point tables.
75
76## Exporting symbols
77
Peter Kasting5e04bd32019-05-21 21:44:1078Symbols can be exported (made visible outside of a shared library/DLL) by
79annotating with a `<COMPONENT>_EXPORT` macro name (where `<COMPONENT>` is the
80name of the component being built, e.g. BASE, NET, CONTENT, etc.). Class
81annotations should precede the class name:
brettwf0e606a52016-07-06 21:17:2082```c++
83class FOO_EXPORT Foo {
84 void Bar();
85 void Baz();
86 // ...
87};
88```
89
90Function annotations should precede the return type:
91```c++
92class FooSingleton {
93 FOO_EXPORT Foo& GetFoo();
Jeremy Roman312202882019-02-19 21:43:5094 FOO_EXPORT Foo& SetFooForTesting(Foo* foo);
Peter Kasting5e04bd32019-05-21 21:44:1095 void SetFoo(Foo* foo); // Not exported.
brettwf0e606a52016-07-06 21:17:2096};
97```
98
brettwf0e606a52016-07-06 21:17:2099## Multiple inheritance
100
101Multiple inheritance and virtual inheritance are permitted in Chromium code,
102but discouraged (beyond the "interface" style of inheritance allowed by the
103Google style guide, for which we do not require classes to have the "Interface"
104suffix). Consider whether composition could solve the problem instead.
105
106## Inline functions
107
108Simple accessors should generally be the only inline functions. These should be
Peter Kasting5e04bd32019-05-21 21:44:10109named using `snake_case()`. Virtual functions should never be declared this way.
brettwf0e606a52016-07-06 21:17:20110
111## Logging
112
113Remove most logging calls before checking in. Unless you're adding temporary
114logging to track down a specific bug, and you have a plan for how to collect
115the logged data from user machines, you should generally not add logging
116statements.
117
118For the rare case when logging needs to stay in the codebase for a while,
119prefer `DVLOG(1)` to other logging methods. This avoids bloating the release
120executable and in debug can be selectively enabled at runtime by command-line
121arguments:
Peter Kasting5e04bd32019-05-21 21:44:10122 * `--v=n` sets the global log level to n (default 0). All log statements with
123 a log level less than or equal to the global level will be printed.
brettwf0e606a52016-07-06 21:17:20124 * `--vmodule=mod=n[,mod=n,...]` overrides the global log level for the module
125 mod. Supplying the string foo for mod will affect all files named foo.cc,
126 while supplying a wildcard like `*bar/baz*` will affect all files with
127 `bar/baz` in their full pathnames.
128
129## Platform-specific code
130
131To `#ifdef` code for specific platforms, use the macros defined in
132`build/build_config.h` and in the Chromium build config files, not other macros
Tommy C. Li1a13764a2018-09-17 21:18:34133set by specific compilers or build environments (e.g. `WIN32`).
brettwf0e606a52016-07-06 21:17:20134
135Place platform-specific #includes in their own section below the "normal"
136`#includes`. Repeat the standard `#include` order within this section:
137
138```c++
139 #include "foo/foo.h"
140
141 #include <stdint.h>
142 #include <algorithm>
143
144 #include "base/strings/utf_string_conversions.h"
Xiaohan Wang0727d882022-01-21 03:03:43145 #include "build/build_config.h"
brettwf0e606a52016-07-06 21:17:20146 #include "chrome/common/render_messages.h"
147
Xiaohan Wang0727d882022-01-21 03:03:43148 #if BUILDFLAG(IS_WIN)
brettwf0e606a52016-07-06 21:17:20149 #include <windows.h>
Robert Liaoc7c9a1c2017-10-18 01:41:31150 #include "base/win/com_init_util.h"
Xiaohan Wang0727d882022-01-21 03:03:43151 #elif BUILDFLAG(IS_POSIX)
brettwf0e606a52016-07-06 21:17:20152 #include "base/posix/global_descriptors.h"
153 #endif
154```
155
156## Types
157
Dominick Ng71a699a2022-01-26 23:46:57158 * Refer to the [Mojo style
159 guide](https://chromium.googlesource.com/chromium/src/+/main/docs/security/mojo.md)
160 when working with types that will be passed across network or process
161 boundaries. For example, explicitly-sized integral types must be used for
162 safety, since the sending and receiving ends may not have been compiled
163 with the same sizes for things like `int` and `size_t`.
brettwf0e606a52016-07-06 21:17:20164 * Use `size_t` for object and allocation sizes, object counts, array and
Peter Kasting5e04bd32019-05-21 21:44:10165 pointer offsets, vector indices, and so on. This prevents casts when
166 dealing with STL APIs, and if followed consistently across the codebase,
167 minimizes casts elsewhere.
168 * Occasionally classes may have a good reason to use a type other than
169 `size_t` for one of these concepts, e.g. as a storage space optimization. In
170 these cases, continue to use `size_t` in public-facing function
171 declarations, and continue to use unsigned types internally (e.g.
172 `uint32_t`).
Dominick Ng71a699a2022-01-26 23:46:57173 * Follow the [integer semantics
174 guide](https://chromium.googlesource.com/chromium/src/+/main/docs/security/integer-semantics.md)
175 for all arithmetic conversions and calculations used in memory management
176 or passed across network or process boundaries. In other circumstances,
177 follow [Google C++ casting
Dana Fried74a18892018-09-13 19:10:01178 conventions](https://google.github.io/styleguide/cppguide.html#Casting)
179 to convert arithmetic types when you know the conversion is safe. Use
Chris Palmer8218b8572019-02-26 00:19:16180 `checked_cast<T>` (from `base/numerics/safe_conversions.h`) when you need to
181 `CHECK` that the source value is in range for the destination type. Use
182 `saturated_cast<T>` if you instead wish to clamp out-of-range values.
Peter Kasting5e04bd32019-05-21 21:44:10183 `CheckedNumeric` is an ergonomic way to perform safe arithmetic and casting
184 in many cases.
Peter Kasting9e210a522021-03-20 15:45:42185 * The Google Style Guide [bans
186 UTF-16](https://google.github.io/styleguide/cppguide.html#Non-ASCII_Characters).
187 For various reasons, Chromium uses UTF-16 extensively. Use `std::u16string`
188 and `char16_t*` for 16-bit strings, `u"..."` to declare UTF-16 literals, and
189 either the actual characters or the `\uXXXX` or `\UXXXXXXXX` escapes for
190 Unicode characters. Avoid `\xXX...`-style escapes, which can cause subtle
191 problems if someone attempts to change the type of string that holds the
192 literal. In code used only on Windows, it may be necessary to use
193 `std::wstring` and `wchar_t*`; these are legal, but note that they are
194 distinct types and are often not 16-bit on other platforms.
brettwf0e606a52016-07-06 21:17:20195
196## Object ownership and calling conventions
197
198When functions need to take raw or smart pointers as parameters, use the
199following conventions. Here we refer to the parameter type as `T` and name as
200`t`.
Peter Kasting5e04bd32019-05-21 21:44:10201 * If the function does not modify `t`'s ownership, declare the param as `T*`.
202 The caller is expected to ensure `t` stays alive as long as necessary,
203 generally through the duration of the call. Exception: In rare cases (e.g.
204 using lambdas with STL algorithms over containers of `unique_ptr<>`s), you
205 may be forced to declare the param as `const std::unique_ptr<T>&`. Do this
206 only when required.
brettwf0e606a52016-07-06 21:17:20207 * If the function takes ownership of a non-refcounted object, declare the
208 param as `std::unique_ptr<T>`.
brettwf0e606a52016-07-06 21:17:20209 * If the function (at least sometimes) takes a ref on a refcounted object,
210 declare the param as `scoped_refptr<T>`. The caller can decide
211 whether it wishes to transfer ownership (by calling `std::move(t)` when
212 passing `t`) or retain its ref (by simply passing t directly).
brettwf0e606a52016-07-06 21:17:20213 * In short, functions should never take ownership of parameters passed as raw
214 pointers, and there should rarely be a need to pass smart pointers by const
215 ref.
216
Gabriel Charetteb62806f4a2019-01-29 21:08:41217Conventions for return values are similar with an important distinction:
218 * Return raw pointers if-and-only-if the caller does not take ownership.
219 * Return `std::unique_ptr<T>` or `scoped_refptr<T>` by value when the impl is
220 handing off ownership.
221 * **Distinction**: Return `const scoped_refptr<T>&` when the impl retains
222 ownership so the caller isn't required to take a ref: this avoids bumping
223 the reference count if the caller doesn't need ownership and also
224 [helps binary size](https://crrev.com/c/1435627)).
brettwf0e606a52016-07-06 21:17:20225
226A great deal of Chromium code predates the above rules. In particular, some
227functions take ownership of params passed as `T*`, or take `const
228scoped_refptr<T>&` instead of `T*`, or return `T*` instead of
229`scoped_refptr<T>` (to avoid refcount churn pre-C++11). Try to clean up such
230code when you find it, or at least not make such usage any more widespread.
231
Lukasz Anforowicz269e41d2021-11-30 18:32:01232## Non-owning pointers in class fields
233
danakj2c782052022-06-30 02:13:48234Use `const raw_ref<T>` or `raw_ptr<T>` for class and struct fields in place of a
235raw C++ reference `T&` or pointer `T*` whenever possible, except in paths that include
Orr Bernstein41ce8f02022-12-20 17:09:39236`/renderer/` or `blink/public/web/`. These are non-owning smart pointers that
danakj2c782052022-06-30 02:13:48237have improved memory-safety over raw pointers and references, and can prevent
238exploitation of a significant percentage of Use-after-Free bugs.
Lukasz Anforowicz269e41d2021-11-30 18:32:01239
danakj2c782052022-06-30 02:13:48240Prefer `const raw_ref<T>` whenever the held pointer will never be null, and it's
241ok to drop the `const` if the internal reference can be reassigned to point to a
242different `T`. Use `raw_ptr<T>` in order to express that the pointer _can_ be
243null. Only `raw_ptr<T>` can be default-constructed, since `raw_ref<T>` disallows
244nullness.
245
246Using `raw_ref<T>` or `raw_ptr<T>` may not be possible in rare cases for
247[performance reasons](../../base/memory/raw_ptr.md#Performance). Additionally,
248`raw_ptr<T>` doesn’t support some C++ scenarios (e.g. `constexpr`, ObjC
249pointers). Tooling will help to encourage use of these types in the future. See
250[raw_ptr.md](../../base/memory/raw_ptr.md#When-to-use-raw_ptr_T) for how to add
251exclusions.
Lukasz Anforowicz269e41d2021-11-30 18:32:01252
Peter Kasting618227f2023-03-02 02:36:42253## thread_local variables
254
255Much code in Chrome needs to be "sequence-aware" rather than "thread-aware". If
256you need a sequence-local variable, see
257[`base::SequenceLocalStorageSlot`](../../base/threading/sequence_local_storage_slot.h).
258
259If you truly need a thread-local variable, then you can use a `thread_local`, as
260long as it complies with the following requirements:
Peter Kastingc242b102023-07-27 20:39:12261 * Its type must satisfy `std::is_trivially_destructible_v<T>`, due to past
262 problems with "spooky action at a distance" during destruction. Note that
263 `raw_ptr<T>` is not a trivially-destructible type and may not be contained
264 in `thread_locals`.
Peter Kasting618227f2023-03-02 02:36:42265 * It must not be exported (e.g. via `COMPONENT_EXPORT`), since this may result
266 in codegen bugs on Mac; and at least on Windows, this probably won't compile
267 in the component build anyway. As a workaround, create an exported getter
268 function that creates a `thread_local` internally and returns a ref to it.
269 * If it lives at class/namespace scope, it must be marked `ABSL_CONST_INIT`,
270 as specified in
271 [the Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html#thread_local).
272 * It must not be constructed inside OOM handlers or any other code that cannot
273 allocate memory, since on POSIX, construction may alloc.
Peter Kasting4f398232023-03-16 01:34:24274
Peter Kasting618227f2023-03-02 02:36:42275If you can't comply with these requirements, consider
276[`base::ThreadLocalOwnedPointer`](../../base/threading/thread_local.h) or
277another nearby low-level utility.
278
brettwf0e606a52016-07-06 21:17:20279## Forward declarations vs. #includes
280
281Unlike the Google style guide, Chromium style prefers forward declarations to
282`#includes` where possible. This can reduce compile times and result in fewer
283files needing recompilation when a header changes.
284
285You can and should use forward declarations for most types passed or returned
286by value, reference, or pointer, or types stored as pointer members or in most
287STL containers. However, if it would otherwise make sense to use a type as a
288member by-value, don't convert it to a pointer just to be able to
289forward-declare the type.
290
291## File headers
292
Peter Kasting5e04bd32019-05-21 21:44:10293All files in Chromium start with a common license header. That header should
294look like this:
brettwf0e606a52016-07-06 21:17:20295
296```c++
Avi Drissman7b017a992022-09-07 15:50:38297// Copyright $YEAR The Chromium Authors
brettwf0e606a52016-07-06 21:17:20298// Use of this source code is governed by a BSD-style license that can be
299// found in the LICENSE file.
300```
301
302Some important notes about this header:
Peter Kasting5e04bd32019-05-21 21:44:10303 * `$YEAR` should be set to the current year at the time a file is created, and
304 not changed thereafter.
Tommy Chiang174366f2022-07-27 16:40:53305 * For files specific to ChromiumOS, replace the word Chromium with the phrase
306 ChromiumOS.
brettwf0e606a52016-07-06 21:17:20307 * The Chromium project hosts mirrors of some upstream open-source projects.
308 When contributing to these portions of the repository, retain the existing
309 file headers.
310
311Use standard `#include` guards in all header files (see the Google style guide
312sections on these for the naming convention). Do not use `#pragma once`;
313historically it was not supported on all platforms, and it does not seem to
314outperform #include guards even on platforms which do support it.
315
Peter Boström835c77052023-03-03 21:33:23316## CHECK(), DCHECK(), NOTREACHED_NORETURN() and NOTREACHED()
brettwf0e606a52016-07-06 21:17:20317
Peter Boström835c77052023-03-03 21:33:23318Use the `CHECK()` family of macros to both document and verify invariants.
319 * Exception: If the invariant is known to be too expensive to verify in
320 production, you may fall back to `DCHECK()`. Do not do this unless
321 necessary.
Peter Boström25052092023-12-09 00:27:24322 * Exception: If your pre-stable coverage is too small to prevent a stability
323 risk once `CHECK()`s hit stable, and failure doesn't obviously result in a
324 crash or security risk, you may use `CHECK(Foo(),
325 base::NotFatalUntil::M120)` with a future milestone to gather non-fatal
326 diagnostics in stable before automatically turning fatal in a later
327 milestone.
Peter Boström835c77052023-03-03 21:33:23328 * Historically, Chromium code used `DCHECK()` in most cases, so a great deal
Vincent Scheibd4a8acc2023-03-16 23:00:07329 of existing code uses `DCHECK()` instead of `CHECK()`. You are encouraged
Peter Boström25052092023-12-09 00:27:24330 to migrate to `CHECK()`s with a trailing `base::NotFatalUntil::M120`
331 argument, as there's stability risk given the under-tested invariant, or add
332 a comment explaining why DCHECK is appropriate given the current guidance.
brettwf0e606a52016-07-06 21:17:20333
Peter Boström835c77052023-03-03 21:33:23334Use `NOTREACHED_NORETURN()` to indicate a piece of code is unreachable. Control
335flow does not leave this call, so there should be no executable statements after
336it (even return statements from non-void functions). The compiler will issue
337dead-code warnings.
338 * Prefer to unconditionally `CHECK()` instead of conditionally hitting a
339 `NOTREACHED[_NORETURN]()`, where feasible.
Peter Boström25052092023-12-09 00:27:24340 * Exception: If your pre-stable coverage is too small to prevent a stability
341 risk once `NOTREACHED_NORETURN()`s hit stable, and failure doesn't obviously
342 result in a crash or security risk, you may use `NOTREACHED(
343 base::NotFatalUntil::M120)` with a future milestone to gather non-fatal
344 diagnostics in stable before automatically turning fatal in a later
345 milestone.
346 * Historically, Chromium code used `NOTREACHED()` for this purpose.
347 [Migrating this code](https://crbug.com/851128) to be fatal (and
348 `[[noreturn]]`) is part of a `kNotReachedIsFatal` experiment.
349
Peter Boström835c77052023-03-03 21:33:23350
351Use `base::ImmediateCrash()` in the rare case where it's necessary to terminate
352the current process for reasons outside its control, that are not violations of
353our invariants.
354
355Use `base::debug::DumpWithoutCrashing()` to generate a crash report but keep
356running in the case where you are investigating some failure but know that it's
357safe to continue execution.
358
359Use `DLOG(FATAL)` (does nothing in production) or `LOG(DFATAL)` (logs an error
360and continues running in production) if you need to log an error in tests from
361production code. From test code, use `ADD_FAILURE()` directly. Do not use these
362for invariant failures. Those should use `CHECK()` or `NOTREACHED_NORETURN()` as
363noted above.
364
365For more details, see [checks.md](checks.md).
brettwf0e606a52016-07-06 21:17:20366
Roland Bockd662a2d2022-07-12 20:55:27367## Test-only code paths in production code
368
369Try to avoid test-only code paths in production code. Such code paths make
370production code behave differently in tests. This makes both tests and
371production code hard to reason about. Consider dependency injection, fake
372classes, etc to avoid such code paths.
373
374However, if a test-only path in production code cannot be avoided, instrument
375that code path with `CHECK_IS_TEST();` to assert that the code is only run in
376tests.
377
378```c++
379// `profile_manager` may not be available in tests.
380if (!profile_manager) {
381 CHECK_IS_TEST();
382 return std::string();
383}
384```
385
386`CHECK_IS_TEST();` will crash outside of tests. This asserts that the test-only
387code path is not accidentally or maliciously taken in production.
388
brettwf0e606a52016-07-06 21:17:20389## Miscellany
390
391 * Use UTF-8 file encodings and LF line endings.
brettwf0e606a52016-07-06 21:17:20392 * Unit tests and performance tests should be placed in the same directory as
393 the functionality they're testing.
Xiaohan Wangcc517f082019-01-16 01:58:14394 * The [C++ Dos and Don'ts](c++-dos-and-donts.md) page has more helpful
395 information.