blob: 493c5efe3e3444e3bb278cc9b381608476cb65b2 [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 Koshy0b38a322022-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)`.
66
brettwf0e606a52016-07-06 21:17:2067## Unnamed namespaces
68
69Items local to a .cc file should be wrapped in an unnamed namespace. While some
70such items are already file-scope by default in C++, not all are; also, shared
71objects on Linux builds export all symbols, so unnamed namespaces (which
72restrict these symbols to the compilation unit) improve function call cost and
73reduce the size of entry point tables.
74
75## Exporting symbols
76
Peter Kasting5e04bd32019-05-21 21:44:1077Symbols can be exported (made visible outside of a shared library/DLL) by
78annotating with a `<COMPONENT>_EXPORT` macro name (where `<COMPONENT>` is the
79name of the component being built, e.g. BASE, NET, CONTENT, etc.). Class
80annotations should precede the class name:
brettwf0e606a52016-07-06 21:17:2081```c++
82class FOO_EXPORT Foo {
83 void Bar();
84 void Baz();
85 // ...
86};
87```
88
89Function annotations should precede the return type:
90```c++
91class FooSingleton {
92 FOO_EXPORT Foo& GetFoo();
Jeremy Roman312202882019-02-19 21:43:5093 FOO_EXPORT Foo& SetFooForTesting(Foo* foo);
Peter Kasting5e04bd32019-05-21 21:44:1094 void SetFoo(Foo* foo); // Not exported.
brettwf0e606a52016-07-06 21:17:2095};
96```
97
brettwf0e606a52016-07-06 21:17:2098## Multiple inheritance
99
100Multiple inheritance and virtual inheritance are permitted in Chromium code,
101but discouraged (beyond the "interface" style of inheritance allowed by the
102Google style guide, for which we do not require classes to have the "Interface"
103suffix). Consider whether composition could solve the problem instead.
104
105## Inline functions
106
107Simple accessors should generally be the only inline functions. These should be
Peter Kasting5e04bd32019-05-21 21:44:10108named using `snake_case()`. Virtual functions should never be declared this way.
brettwf0e606a52016-07-06 21:17:20109
110## Logging
111
112Remove most logging calls before checking in. Unless you're adding temporary
113logging to track down a specific bug, and you have a plan for how to collect
114the logged data from user machines, you should generally not add logging
115statements.
116
117For the rare case when logging needs to stay in the codebase for a while,
118prefer `DVLOG(1)` to other logging methods. This avoids bloating the release
119executable and in debug can be selectively enabled at runtime by command-line
120arguments:
Peter Kasting5e04bd32019-05-21 21:44:10121 * `--v=n` sets the global log level to n (default 0). All log statements with
122 a log level less than or equal to the global level will be printed.
brettwf0e606a52016-07-06 21:17:20123 * `--vmodule=mod=n[,mod=n,...]` overrides the global log level for the module
124 mod. Supplying the string foo for mod will affect all files named foo.cc,
125 while supplying a wildcard like `*bar/baz*` will affect all files with
126 `bar/baz` in their full pathnames.
127
128## Platform-specific code
129
130To `#ifdef` code for specific platforms, use the macros defined in
131`build/build_config.h` and in the Chromium build config files, not other macros
Tommy C. Li1a13764a2018-09-17 21:18:34132set by specific compilers or build environments (e.g. `WIN32`).
brettwf0e606a52016-07-06 21:17:20133
134Place platform-specific #includes in their own section below the "normal"
135`#includes`. Repeat the standard `#include` order within this section:
136
137```c++
138 #include "foo/foo.h"
139
140 #include <stdint.h>
141 #include <algorithm>
142
143 #include "base/strings/utf_string_conversions.h"
Xiaohan Wang0727d882022-01-21 03:03:43144 #include "build/build_config.h"
brettwf0e606a52016-07-06 21:17:20145 #include "chrome/common/render_messages.h"
146
Xiaohan Wang0727d882022-01-21 03:03:43147 #if BUILDFLAG(IS_WIN)
brettwf0e606a52016-07-06 21:17:20148 #include <windows.h>
Robert Liaoc7c9a1c2017-10-18 01:41:31149 #include "base/win/com_init_util.h"
Xiaohan Wang0727d882022-01-21 03:03:43150 #elif BUILDFLAG(IS_POSIX)
brettwf0e606a52016-07-06 21:17:20151 #include "base/posix/global_descriptors.h"
152 #endif
153```
154
155## Types
156
Dominick Ng71a699a2022-01-26 23:46:57157 * Refer to the [Mojo style
158 guide](https://chromium.googlesource.com/chromium/src/+/main/docs/security/mojo.md)
159 when working with types that will be passed across network or process
160 boundaries. For example, explicitly-sized integral types must be used for
161 safety, since the sending and receiving ends may not have been compiled
162 with the same sizes for things like `int` and `size_t`.
brettwf0e606a52016-07-06 21:17:20163 * Use `size_t` for object and allocation sizes, object counts, array and
Peter Kasting5e04bd32019-05-21 21:44:10164 pointer offsets, vector indices, and so on. This prevents casts when
165 dealing with STL APIs, and if followed consistently across the codebase,
166 minimizes casts elsewhere.
167 * Occasionally classes may have a good reason to use a type other than
168 `size_t` for one of these concepts, e.g. as a storage space optimization. In
169 these cases, continue to use `size_t` in public-facing function
170 declarations, and continue to use unsigned types internally (e.g.
171 `uint32_t`).
Dominick Ng71a699a2022-01-26 23:46:57172 * Follow the [integer semantics
173 guide](https://chromium.googlesource.com/chromium/src/+/main/docs/security/integer-semantics.md)
174 for all arithmetic conversions and calculations used in memory management
175 or passed across network or process boundaries. In other circumstances,
176 follow [Google C++ casting
Dana Fried74a18892018-09-13 19:10:01177 conventions](https://google.github.io/styleguide/cppguide.html#Casting)
178 to convert arithmetic types when you know the conversion is safe. Use
Chris Palmer8218b8572019-02-26 00:19:16179 `checked_cast<T>` (from `base/numerics/safe_conversions.h`) when you need to
180 `CHECK` that the source value is in range for the destination type. Use
181 `saturated_cast<T>` if you instead wish to clamp out-of-range values.
Peter Kasting5e04bd32019-05-21 21:44:10182 `CheckedNumeric` is an ergonomic way to perform safe arithmetic and casting
183 in many cases.
Peter Kasting9e210a522021-03-20 15:45:42184 * The Google Style Guide [bans
185 UTF-16](https://google.github.io/styleguide/cppguide.html#Non-ASCII_Characters).
186 For various reasons, Chromium uses UTF-16 extensively. Use `std::u16string`
187 and `char16_t*` for 16-bit strings, `u"..."` to declare UTF-16 literals, and
188 either the actual characters or the `\uXXXX` or `\UXXXXXXXX` escapes for
189 Unicode characters. Avoid `\xXX...`-style escapes, which can cause subtle
190 problems if someone attempts to change the type of string that holds the
191 literal. In code used only on Windows, it may be necessary to use
192 `std::wstring` and `wchar_t*`; these are legal, but note that they are
193 distinct types and are often not 16-bit on other platforms.
brettwf0e606a52016-07-06 21:17:20194
195## Object ownership and calling conventions
196
197When functions need to take raw or smart pointers as parameters, use the
198following conventions. Here we refer to the parameter type as `T` and name as
199`t`.
Peter Kasting5e04bd32019-05-21 21:44:10200 * If the function does not modify `t`'s ownership, declare the param as `T*`.
201 The caller is expected to ensure `t` stays alive as long as necessary,
202 generally through the duration of the call. Exception: In rare cases (e.g.
203 using lambdas with STL algorithms over containers of `unique_ptr<>`s), you
204 may be forced to declare the param as `const std::unique_ptr<T>&`. Do this
205 only when required.
brettwf0e606a52016-07-06 21:17:20206 * If the function takes ownership of a non-refcounted object, declare the
207 param as `std::unique_ptr<T>`.
brettwf0e606a52016-07-06 21:17:20208 * If the function (at least sometimes) takes a ref on a refcounted object,
209 declare the param as `scoped_refptr<T>`. The caller can decide
210 whether it wishes to transfer ownership (by calling `std::move(t)` when
211 passing `t`) or retain its ref (by simply passing t directly).
brettwf0e606a52016-07-06 21:17:20212 * In short, functions should never take ownership of parameters passed as raw
213 pointers, and there should rarely be a need to pass smart pointers by const
214 ref.
215
Gabriel Charetteb62806f4a2019-01-29 21:08:41216Conventions for return values are similar with an important distinction:
217 * Return raw pointers if-and-only-if the caller does not take ownership.
218 * Return `std::unique_ptr<T>` or `scoped_refptr<T>` by value when the impl is
219 handing off ownership.
220 * **Distinction**: Return `const scoped_refptr<T>&` when the impl retains
221 ownership so the caller isn't required to take a ref: this avoids bumping
222 the reference count if the caller doesn't need ownership and also
223 [helps binary size](https://crrev.com/c/1435627)).
brettwf0e606a52016-07-06 21:17:20224
225A great deal of Chromium code predates the above rules. In particular, some
226functions take ownership of params passed as `T*`, or take `const
227scoped_refptr<T>&` instead of `T*`, or return `T*` instead of
228`scoped_refptr<T>` (to avoid refcount churn pre-C++11). Try to clean up such
229code when you find it, or at least not make such usage any more widespread.
230
Lukasz Anforowicz269e41d2021-11-30 18:32:01231## Non-owning pointers in class fields
232
danakj2c782052022-06-30 02:13:48233Use `const raw_ref<T>` or `raw_ptr<T>` for class and struct fields in place of a
234raw C++ reference `T&` or pointer `T*` whenever possible, except in paths that include
Orr Bernstein41ce8f02022-12-20 17:09:39235`/renderer/` or `blink/public/web/`. These are non-owning smart pointers that
danakj2c782052022-06-30 02:13:48236have improved memory-safety over raw pointers and references, and can prevent
237exploitation of a significant percentage of Use-after-Free bugs.
Lukasz Anforowicz269e41d2021-11-30 18:32:01238
danakj2c782052022-06-30 02:13:48239Prefer `const raw_ref<T>` whenever the held pointer will never be null, and it's
240ok to drop the `const` if the internal reference can be reassigned to point to a
241different `T`. Use `raw_ptr<T>` in order to express that the pointer _can_ be
242null. Only `raw_ptr<T>` can be default-constructed, since `raw_ref<T>` disallows
243nullness.
244
245Using `raw_ref<T>` or `raw_ptr<T>` may not be possible in rare cases for
246[performance reasons](../../base/memory/raw_ptr.md#Performance). Additionally,
247`raw_ptr<T>` doesn’t support some C++ scenarios (e.g. `constexpr`, ObjC
248pointers). Tooling will help to encourage use of these types in the future. See
249[raw_ptr.md](../../base/memory/raw_ptr.md#When-to-use-raw_ptr_T) for how to add
250exclusions.
Lukasz Anforowicz269e41d2021-11-30 18:32:01251
Peter Kasting618227f2023-03-02 02:36:42252## thread_local variables
253
254Much code in Chrome needs to be "sequence-aware" rather than "thread-aware". If
255you need a sequence-local variable, see
256[`base::SequenceLocalStorageSlot`](../../base/threading/sequence_local_storage_slot.h).
257
258If you truly need a thread-local variable, then you can use a `thread_local`, as
259long as it complies with the following requirements:
Peter Kastingc242b102023-07-27 20:39:12260 * Its type must satisfy `std::is_trivially_destructible_v<T>`, due to past
261 problems with "spooky action at a distance" during destruction. Note that
262 `raw_ptr<T>` is not a trivially-destructible type and may not be contained
263 in `thread_locals`.
Peter Kasting618227f2023-03-02 02:36:42264 * It must not be exported (e.g. via `COMPONENT_EXPORT`), since this may result
265 in codegen bugs on Mac; and at least on Windows, this probably won't compile
266 in the component build anyway. As a workaround, create an exported getter
267 function that creates a `thread_local` internally and returns a ref to it.
268 * If it lives at class/namespace scope, it must be marked `ABSL_CONST_INIT`,
269 as specified in
270 [the Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html#thread_local).
271 * It must not be constructed inside OOM handlers or any other code that cannot
272 allocate memory, since on POSIX, construction may alloc.
Peter Kasting4f398232023-03-16 01:34:24273
Peter Kasting618227f2023-03-02 02:36:42274If you can't comply with these requirements, consider
275[`base::ThreadLocalOwnedPointer`](../../base/threading/thread_local.h) or
276another nearby low-level utility.
277
brettwf0e606a52016-07-06 21:17:20278## Forward declarations vs. #includes
279
280Unlike the Google style guide, Chromium style prefers forward declarations to
281`#includes` where possible. This can reduce compile times and result in fewer
282files needing recompilation when a header changes.
283
284You can and should use forward declarations for most types passed or returned
285by value, reference, or pointer, or types stored as pointer members or in most
286STL containers. However, if it would otherwise make sense to use a type as a
287member by-value, don't convert it to a pointer just to be able to
288forward-declare the type.
289
290## File headers
291
Peter Kasting5e04bd32019-05-21 21:44:10292All files in Chromium start with a common license header. That header should
293look like this:
brettwf0e606a52016-07-06 21:17:20294
295```c++
Avi Drissman7b017a992022-09-07 15:50:38296// Copyright $YEAR The Chromium Authors
brettwf0e606a52016-07-06 21:17:20297// Use of this source code is governed by a BSD-style license that can be
298// found in the LICENSE file.
299```
300
301Some important notes about this header:
Peter Kasting5e04bd32019-05-21 21:44:10302 * `$YEAR` should be set to the current year at the time a file is created, and
303 not changed thereafter.
Tommy Chiang174366f2022-07-27 16:40:53304 * For files specific to ChromiumOS, replace the word Chromium with the phrase
305 ChromiumOS.
brettwf0e606a52016-07-06 21:17:20306 * The Chromium project hosts mirrors of some upstream open-source projects.
307 When contributing to these portions of the repository, retain the existing
308 file headers.
309
310Use standard `#include` guards in all header files (see the Google style guide
311sections on these for the naming convention). Do not use `#pragma once`;
312historically it was not supported on all platforms, and it does not seem to
313outperform #include guards even on platforms which do support it.
314
Peter Boström835c77052023-03-03 21:33:23315## CHECK(), DCHECK(), NOTREACHED_NORETURN() and NOTREACHED()
brettwf0e606a52016-07-06 21:17:20316
Peter Boström835c77052023-03-03 21:33:23317Use the `CHECK()` family of macros to both document and verify invariants.
318 * Exception: If the invariant is known to be too expensive to verify in
319 production, you may fall back to `DCHECK()`. Do not do this unless
320 necessary.
321 * Historically, Chromium code used `DCHECK()` in most cases, so a great deal
Vincent Scheibd4a8acc2023-03-16 23:00:07322 of existing code uses `DCHECK()` instead of `CHECK()`. You are encouraged
323 to migrate to `CHECK()` or add a comment explaining why DCHECK is
324 appropriate given the current guidance.
brettwf0e606a52016-07-06 21:17:20325
Peter Boström835c77052023-03-03 21:33:23326Use `NOTREACHED_NORETURN()` to indicate a piece of code is unreachable. Control
327flow does not leave this call, so there should be no executable statements after
328it (even return statements from non-void functions). The compiler will issue
329dead-code warnings.
330 * Prefer to unconditionally `CHECK()` instead of conditionally hitting a
331 `NOTREACHED[_NORETURN]()`, where feasible.
332 * Historically, Chromium code used `NOTREACHED()` for this purpose. This is
333 not annotated as `[[noreturn]]`. You are welcome (and encouraged) to migrate
334 to `NOTREACHED_NORETURN()`, just expect to need to make some tweaks to
335 surrounding code.
336
337Use `base::ImmediateCrash()` in the rare case where it's necessary to terminate
338the current process for reasons outside its control, that are not violations of
339our invariants.
340
341Use `base::debug::DumpWithoutCrashing()` to generate a crash report but keep
342running in the case where you are investigating some failure but know that it's
343safe to continue execution.
344
345Use `DLOG(FATAL)` (does nothing in production) or `LOG(DFATAL)` (logs an error
346and continues running in production) if you need to log an error in tests from
347production code. From test code, use `ADD_FAILURE()` directly. Do not use these
348for invariant failures. Those should use `CHECK()` or `NOTREACHED_NORETURN()` as
349noted above.
350
351For more details, see [checks.md](checks.md).
brettwf0e606a52016-07-06 21:17:20352
Roland Bockd662a2d2022-07-12 20:55:27353## Test-only code paths in production code
354
355Try to avoid test-only code paths in production code. Such code paths make
356production code behave differently in tests. This makes both tests and
357production code hard to reason about. Consider dependency injection, fake
358classes, etc to avoid such code paths.
359
360However, if a test-only path in production code cannot be avoided, instrument
361that code path with `CHECK_IS_TEST();` to assert that the code is only run in
362tests.
363
364```c++
365// `profile_manager` may not be available in tests.
366if (!profile_manager) {
367 CHECK_IS_TEST();
368 return std::string();
369}
370```
371
372`CHECK_IS_TEST();` will crash outside of tests. This asserts that the test-only
373code path is not accidentally or maliciously taken in production.
374
brettwf0e606a52016-07-06 21:17:20375## Miscellany
376
377 * Use UTF-8 file encodings and LF line endings.
brettwf0e606a52016-07-06 21:17:20378 * Unit tests and performance tests should be placed in the same directory as
379 the functionality they're testing.
Xiaohan Wangcc517f082019-01-16 01:58:14380 * The [C++ Dos and Don'ts](c++-dos-and-donts.md) page has more helpful
381 information.