blob: f2b9b2960492f80edaa7bddd949591efbf3d3a2a [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)`.
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
Erik Chencd92bd22024-02-02 04:09:54113Remove all logging before checking in code. The exception is temporary logging
114to track down a specific bug. This should be a rare exception, and you should
115have a plan for how to manually collect/use the logged data. Afterwards you
116should remove the logging. Note that logs are not present in crashes. Use
117`base::debug::ScopedCrashKeyString`
118([link](https://chromium.googlesource.com/chromium/src/+/main/base/debug/crash_logging.h))
119for that.
brettwf0e606a52016-07-06 21:17:20120
121For the rare case when logging needs to stay in the codebase for a while,
122prefer `DVLOG(1)` to other logging methods. This avoids bloating the release
123executable and in debug can be selectively enabled at runtime by command-line
124arguments:
Peter Kasting5e04bd32019-05-21 21:44:10125 * `--v=n` sets the global log level to n (default 0). All log statements with
126 a log level less than or equal to the global level will be printed.
brettwf0e606a52016-07-06 21:17:20127 * `--vmodule=mod=n[,mod=n,...]` overrides the global log level for the module
128 mod. Supplying the string foo for mod will affect all files named foo.cc,
129 while supplying a wildcard like `*bar/baz*` will affect all files with
130 `bar/baz` in their full pathnames.
131
Erik Chencd92bd22024-02-02 04:09:54132Rationale:
133* Logging is expensive: binary size, runtime.
134* Logging quickly loses utility as more components emit logs: too much noise,
135 not enough signal.
136* Logging is often used to document impossible edge cases which should be
137 enforced with CHECKs. The latter makes it easier to reason about the code, and
138 can result in more performant binaries.
139
brettwf0e606a52016-07-06 21:17:20140## Platform-specific code
141
142To `#ifdef` code for specific platforms, use the macros defined in
143`build/build_config.h` and in the Chromium build config files, not other macros
Tommy C. Li1a13764a2018-09-17 21:18:34144set by specific compilers or build environments (e.g. `WIN32`).
brettwf0e606a52016-07-06 21:17:20145
146Place platform-specific #includes in their own section below the "normal"
147`#includes`. Repeat the standard `#include` order within this section:
148
149```c++
150 #include "foo/foo.h"
151
152 #include <stdint.h>
153 #include <algorithm>
154
155 #include "base/strings/utf_string_conversions.h"
Xiaohan Wang0727d882022-01-21 03:03:43156 #include "build/build_config.h"
brettwf0e606a52016-07-06 21:17:20157 #include "chrome/common/render_messages.h"
158
Xiaohan Wang0727d882022-01-21 03:03:43159 #if BUILDFLAG(IS_WIN)
brettwf0e606a52016-07-06 21:17:20160 #include <windows.h>
Robert Liaoc7c9a1c2017-10-18 01:41:31161 #include "base/win/com_init_util.h"
Xiaohan Wang0727d882022-01-21 03:03:43162 #elif BUILDFLAG(IS_POSIX)
brettwf0e606a52016-07-06 21:17:20163 #include "base/posix/global_descriptors.h"
164 #endif
165```
166
167## Types
168
Dominick Ng71a699a2022-01-26 23:46:57169 * Refer to the [Mojo style
170 guide](https://chromium.googlesource.com/chromium/src/+/main/docs/security/mojo.md)
171 when working with types that will be passed across network or process
172 boundaries. For example, explicitly-sized integral types must be used for
173 safety, since the sending and receiving ends may not have been compiled
174 with the same sizes for things like `int` and `size_t`.
brettwf0e606a52016-07-06 21:17:20175 * Use `size_t` for object and allocation sizes, object counts, array and
Peter Kasting5e04bd32019-05-21 21:44:10176 pointer offsets, vector indices, and so on. This prevents casts when
177 dealing with STL APIs, and if followed consistently across the codebase,
178 minimizes casts elsewhere.
179 * Occasionally classes may have a good reason to use a type other than
180 `size_t` for one of these concepts, e.g. as a storage space optimization. In
181 these cases, continue to use `size_t` in public-facing function
182 declarations, and continue to use unsigned types internally (e.g.
183 `uint32_t`).
Dominick Ng71a699a2022-01-26 23:46:57184 * Follow the [integer semantics
185 guide](https://chromium.googlesource.com/chromium/src/+/main/docs/security/integer-semantics.md)
186 for all arithmetic conversions and calculations used in memory management
187 or passed across network or process boundaries. In other circumstances,
188 follow [Google C++ casting
Dana Fried74a18892018-09-13 19:10:01189 conventions](https://google.github.io/styleguide/cppguide.html#Casting)
190 to convert arithmetic types when you know the conversion is safe. Use
Chris Palmer8218b8572019-02-26 00:19:16191 `checked_cast<T>` (from `base/numerics/safe_conversions.h`) when you need to
192 `CHECK` that the source value is in range for the destination type. Use
193 `saturated_cast<T>` if you instead wish to clamp out-of-range values.
Peter Kasting5e04bd32019-05-21 21:44:10194 `CheckedNumeric` is an ergonomic way to perform safe arithmetic and casting
195 in many cases.
Peter Kasting9e210a522021-03-20 15:45:42196 * The Google Style Guide [bans
197 UTF-16](https://google.github.io/styleguide/cppguide.html#Non-ASCII_Characters).
198 For various reasons, Chromium uses UTF-16 extensively. Use `std::u16string`
199 and `char16_t*` for 16-bit strings, `u"..."` to declare UTF-16 literals, and
200 either the actual characters or the `\uXXXX` or `\UXXXXXXXX` escapes for
201 Unicode characters. Avoid `\xXX...`-style escapes, which can cause subtle
202 problems if someone attempts to change the type of string that holds the
203 literal. In code used only on Windows, it may be necessary to use
204 `std::wstring` and `wchar_t*`; these are legal, but note that they are
205 distinct types and are often not 16-bit on other platforms.
brettwf0e606a52016-07-06 21:17:20206
207## Object ownership and calling conventions
208
209When functions need to take raw or smart pointers as parameters, use the
210following conventions. Here we refer to the parameter type as `T` and name as
211`t`.
Peter Kasting5e04bd32019-05-21 21:44:10212 * If the function does not modify `t`'s ownership, declare the param as `T*`.
213 The caller is expected to ensure `t` stays alive as long as necessary,
214 generally through the duration of the call. Exception: In rare cases (e.g.
215 using lambdas with STL algorithms over containers of `unique_ptr<>`s), you
216 may be forced to declare the param as `const std::unique_ptr<T>&`. Do this
217 only when required.
brettwf0e606a52016-07-06 21:17:20218 * If the function takes ownership of a non-refcounted object, declare the
219 param as `std::unique_ptr<T>`.
brettwf0e606a52016-07-06 21:17:20220 * If the function (at least sometimes) takes a ref on a refcounted object,
221 declare the param as `scoped_refptr<T>`. The caller can decide
222 whether it wishes to transfer ownership (by calling `std::move(t)` when
223 passing `t`) or retain its ref (by simply passing t directly).
brettwf0e606a52016-07-06 21:17:20224 * In short, functions should never take ownership of parameters passed as raw
225 pointers, and there should rarely be a need to pass smart pointers by const
226 ref.
227
Gabriel Charetteb62806f4a2019-01-29 21:08:41228Conventions for return values are similar with an important distinction:
229 * Return raw pointers if-and-only-if the caller does not take ownership.
230 * Return `std::unique_ptr<T>` or `scoped_refptr<T>` by value when the impl is
231 handing off ownership.
232 * **Distinction**: Return `const scoped_refptr<T>&` when the impl retains
233 ownership so the caller isn't required to take a ref: this avoids bumping
234 the reference count if the caller doesn't need ownership and also
235 [helps binary size](https://crrev.com/c/1435627)).
brettwf0e606a52016-07-06 21:17:20236
237A great deal of Chromium code predates the above rules. In particular, some
238functions take ownership of params passed as `T*`, or take `const
239scoped_refptr<T>&` instead of `T*`, or return `T*` instead of
240`scoped_refptr<T>` (to avoid refcount churn pre-C++11). Try to clean up such
241code when you find it, or at least not make such usage any more widespread.
242
Lukasz Anforowicz269e41d2021-11-30 18:32:01243## Non-owning pointers in class fields
244
danakj2c782052022-06-30 02:13:48245Use `const raw_ref<T>` or `raw_ptr<T>` for class and struct fields in place of a
246raw C++ reference `T&` or pointer `T*` whenever possible, except in paths that include
Orr Bernstein41ce8f02022-12-20 17:09:39247`/renderer/` or `blink/public/web/`. These are non-owning smart pointers that
danakj2c782052022-06-30 02:13:48248have improved memory-safety over raw pointers and references, and can prevent
249exploitation of a significant percentage of Use-after-Free bugs.
Lukasz Anforowicz269e41d2021-11-30 18:32:01250
danakj2c782052022-06-30 02:13:48251Prefer `const raw_ref<T>` whenever the held pointer will never be null, and it's
252ok to drop the `const` if the internal reference can be reassigned to point to a
253different `T`. Use `raw_ptr<T>` in order to express that the pointer _can_ be
254null. Only `raw_ptr<T>` can be default-constructed, since `raw_ref<T>` disallows
255nullness.
256
257Using `raw_ref<T>` or `raw_ptr<T>` may not be possible in rare cases for
258[performance reasons](../../base/memory/raw_ptr.md#Performance). Additionally,
259`raw_ptr<T>` doesn’t support some C++ scenarios (e.g. `constexpr`, ObjC
260pointers). Tooling will help to encourage use of these types in the future. See
261[raw_ptr.md](../../base/memory/raw_ptr.md#When-to-use-raw_ptr_T) for how to add
262exclusions.
Lukasz Anforowicz269e41d2021-11-30 18:32:01263
Peter Kasting618227f2023-03-02 02:36:42264## thread_local variables
265
266Much code in Chrome needs to be "sequence-aware" rather than "thread-aware". If
267you need a sequence-local variable, see
268[`base::SequenceLocalStorageSlot`](../../base/threading/sequence_local_storage_slot.h).
269
270If you truly need a thread-local variable, then you can use a `thread_local`, as
271long as it complies with the following requirements:
Peter Kastingc242b102023-07-27 20:39:12272 * Its type must satisfy `std::is_trivially_destructible_v<T>`, due to past
273 problems with "spooky action at a distance" during destruction. Note that
274 `raw_ptr<T>` is not a trivially-destructible type and may not be contained
275 in `thread_locals`.
Peter Kasting618227f2023-03-02 02:36:42276 * It must not be exported (e.g. via `COMPONENT_EXPORT`), since this may result
277 in codegen bugs on Mac; and at least on Windows, this probably won't compile
278 in the component build anyway. As a workaround, create an exported getter
279 function that creates a `thread_local` internally and returns a ref to it.
280 * If it lives at class/namespace scope, it must be marked `ABSL_CONST_INIT`,
281 as specified in
282 [the Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html#thread_local).
283 * It must not be constructed inside OOM handlers or any other code that cannot
284 allocate memory, since on POSIX, construction may alloc.
Peter Kasting4f398232023-03-16 01:34:24285
Peter Kasting618227f2023-03-02 02:36:42286If you can't comply with these requirements, consider
287[`base::ThreadLocalOwnedPointer`](../../base/threading/thread_local.h) or
288another nearby low-level utility.
289
brettwf0e606a52016-07-06 21:17:20290## Forward declarations vs. #includes
291
292Unlike the Google style guide, Chromium style prefers forward declarations to
293`#includes` where possible. This can reduce compile times and result in fewer
294files needing recompilation when a header changes.
295
296You can and should use forward declarations for most types passed or returned
297by value, reference, or pointer, or types stored as pointer members or in most
298STL containers. However, if it would otherwise make sense to use a type as a
299member by-value, don't convert it to a pointer just to be able to
300forward-declare the type.
301
302## File headers
303
Peter Kasting5e04bd32019-05-21 21:44:10304All files in Chromium start with a common license header. That header should
305look like this:
brettwf0e606a52016-07-06 21:17:20306
307```c++
Avi Drissman7b017a992022-09-07 15:50:38308// Copyright $YEAR The Chromium Authors
brettwf0e606a52016-07-06 21:17:20309// Use of this source code is governed by a BSD-style license that can be
310// found in the LICENSE file.
311```
312
313Some important notes about this header:
Peter Kasting5e04bd32019-05-21 21:44:10314 * `$YEAR` should be set to the current year at the time a file is created, and
315 not changed thereafter.
Tommy Chiang174366f2022-07-27 16:40:53316 * For files specific to ChromiumOS, replace the word Chromium with the phrase
317 ChromiumOS.
brettwf0e606a52016-07-06 21:17:20318 * The Chromium project hosts mirrors of some upstream open-source projects.
319 When contributing to these portions of the repository, retain the existing
320 file headers.
321
322Use standard `#include` guards in all header files (see the Google style guide
323sections on these for the naming convention). Do not use `#pragma once`;
324historically it was not supported on all platforms, and it does not seem to
325outperform #include guards even on platforms which do support it.
326
Peter Boström006c93b2024-08-06 00:38:39327## CHECK(), DCHECK() and NOTREACHED()
brettwf0e606a52016-07-06 21:17:20328
Peter Boström835c77052023-03-03 21:33:23329Use the `CHECK()` family of macros to both document and verify invariants.
330 * Exception: If the invariant is known to be too expensive to verify in
331 production, you may fall back to `DCHECK()`. Do not do this unless
332 necessary.
Peter Boström25052092023-12-09 00:27:24333 * Exception: If your pre-stable coverage is too small to prevent a stability
334 risk once `CHECK()`s hit stable, and failure doesn't obviously result in a
335 crash or security risk, you may use `CHECK(Foo(),
336 base::NotFatalUntil::M120)` with a future milestone to gather non-fatal
337 diagnostics in stable before automatically turning fatal in a later
338 milestone.
Peter Boström835c77052023-03-03 21:33:23339 * Historically, Chromium code used `DCHECK()` in most cases, so a great deal
Vincent Scheibd4a8acc2023-03-16 23:00:07340 of existing code uses `DCHECK()` instead of `CHECK()`. You are encouraged
Peter Boström25052092023-12-09 00:27:24341 to migrate to `CHECK()`s with a trailing `base::NotFatalUntil::M120`
342 argument, as there's stability risk given the under-tested invariant, or add
343 a comment explaining why DCHECK is appropriate given the current guidance.
brettwf0e606a52016-07-06 21:17:20344
Peter Boström006c93b2024-08-06 00:38:39345Use `NOTREACHED()` to indicate a piece of code is unreachable. Control flow does
346not leave this call, so there should be no executable statements after it (even
347return statements from non-void functions). The compiler will issue dead-code
348warnings.
Peter Boström835c77052023-03-03 21:33:23349 * Prefer to unconditionally `CHECK()` instead of conditionally hitting a
Peter Boström006c93b2024-08-06 00:38:39350 `NOTREACHED()`, where feasible.
Peter Boström25052092023-12-09 00:27:24351 * Exception: If your pre-stable coverage is too small to prevent a stability
Peter Boström006c93b2024-08-06 00:38:39352 risk once `NOTREACHED()`s hit stable, and failure doesn't obviously
Peter Boström25052092023-12-09 00:27:24353 result in a crash or security risk, you may use `NOTREACHED(
354 base::NotFatalUntil::M120)` with a future milestone to gather non-fatal
355 diagnostics in stable before automatically turning fatal in a later
356 milestone.
Peter Boström835c77052023-03-03 21:33:23357
358Use `base::ImmediateCrash()` in the rare case where it's necessary to terminate
359the current process for reasons outside its control, that are not violations of
360our invariants.
361
362Use `base::debug::DumpWithoutCrashing()` to generate a crash report but keep
363running in the case where you are investigating some failure but know that it's
364safe to continue execution.
365
366Use `DLOG(FATAL)` (does nothing in production) or `LOG(DFATAL)` (logs an error
367and continues running in production) if you need to log an error in tests from
368production code. From test code, use `ADD_FAILURE()` directly. Do not use these
Peter Boström006c93b2024-08-06 00:38:39369for invariant failures. Those should use `CHECK()` or `NOTREACHED()` as noted
370above.
Peter Boström835c77052023-03-03 21:33:23371
372For more details, see [checks.md](checks.md).
brettwf0e606a52016-07-06 21:17:20373
Roland Bockd662a2d2022-07-12 20:55:27374## Test-only code paths in production code
375
376Try to avoid test-only code paths in production code. Such code paths make
377production code behave differently in tests. This makes both tests and
378production code hard to reason about. Consider dependency injection, fake
379classes, etc to avoid such code paths.
380
381However, if a test-only path in production code cannot be avoided, instrument
382that code path with `CHECK_IS_TEST();` to assert that the code is only run in
383tests.
384
385```c++
386// `profile_manager` may not be available in tests.
387if (!profile_manager) {
388 CHECK_IS_TEST();
389 return std::string();
390}
391```
392
393`CHECK_IS_TEST();` will crash outside of tests. This asserts that the test-only
394code path is not accidentally or maliciously taken in production.
395
brettwf0e606a52016-07-06 21:17:20396## Miscellany
397
398 * Use UTF-8 file encodings and LF line endings.
brettwf0e606a52016-07-06 21:17:20399 * Unit tests and performance tests should be placed in the same directory as
400 the functionality they're testing.
Xiaohan Wangcc517f082019-01-16 01:58:14401 * The [C++ Dos and Don'ts](c++-dos-and-donts.md) page has more helpful
402 information.