blob: 5ae0684dc25434ae7c64a9d6086e152c6cbcae33 [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
Peter Kasting777e1302020-06-02 21:44:4025[targets C++17](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
42 to ensure the functions are called only by test files.
Roland Bock1f21a732021-05-20 16:59:5343 * Classes used only for testing should be in a GN build target that is
44 marked `testonly=true`. Tests can depend on such targets, but production
45 code can not.
Dominic Farolino200a14ec2021-07-20 16:42:4046 * While test files generally appear alongside the production code they test,
47 support code for `testonly` targets should be placed in a `test/` subdirectory.
48 For example, see `//mojo/core/core_unittest.cc` and
49 `//mojo/core/test/mojo_test_base.cc`. For test classes used across multiple
50 directories, it might make sense to move them into a nested `test` namespace for
51 clarity.
Dominic Farolinof3d03072021-07-20 15:55:5452 * Despite the Google C++ style guide
53 [deprecating](https://google.github.io/styleguide/cppguide.html#File_Names)
54 the `_unittest.cc` suffix for unit test files, in Chromium we still use this
55 suffix to distinguish unit tests from browser tests, which are written in
56 files with the `_browsertest.cc` suffix.
Tommy C. Li1a13764a2018-09-17 21:18:3457
brettwf0e606a52016-07-06 21:17:2058## Code formatting
59
60 * Put `*` and `&` by the type rather than the variable name.
danakjcd463f12021-02-12 19:53:1361 * In class declarations, group function overrides together within each access
Peter Kasting5e04bd32019-05-21 21:44:1062 control section, with one labeled group per parent class.
brettwf0e606a52016-07-06 21:17:2063 * Prefer `(foo == 0)` to `(0 == foo)`.
64
brettwf0e606a52016-07-06 21:17:2065## Unnamed namespaces
66
67Items local to a .cc file should be wrapped in an unnamed namespace. While some
68such items are already file-scope by default in C++, not all are; also, shared
69objects on Linux builds export all symbols, so unnamed namespaces (which
70restrict these symbols to the compilation unit) improve function call cost and
71reduce the size of entry point tables.
72
73## Exporting symbols
74
Peter Kasting5e04bd32019-05-21 21:44:1075Symbols can be exported (made visible outside of a shared library/DLL) by
76annotating with a `<COMPONENT>_EXPORT` macro name (where `<COMPONENT>` is the
77name of the component being built, e.g. BASE, NET, CONTENT, etc.). Class
78annotations should precede the class name:
brettwf0e606a52016-07-06 21:17:2079```c++
80class FOO_EXPORT Foo {
81 void Bar();
82 void Baz();
83 // ...
84};
85```
86
87Function annotations should precede the return type:
88```c++
89class FooSingleton {
90 FOO_EXPORT Foo& GetFoo();
Jeremy Roman312202882019-02-19 21:43:5091 FOO_EXPORT Foo& SetFooForTesting(Foo* foo);
Peter Kasting5e04bd32019-05-21 21:44:1092 void SetFoo(Foo* foo); // Not exported.
brettwf0e606a52016-07-06 21:17:2093};
94```
95
brettwf0e606a52016-07-06 21:17:2096## Multiple inheritance
97
98Multiple inheritance and virtual inheritance are permitted in Chromium code,
99but discouraged (beyond the "interface" style of inheritance allowed by the
100Google style guide, for which we do not require classes to have the "Interface"
101suffix). Consider whether composition could solve the problem instead.
102
103## Inline functions
104
105Simple accessors should generally be the only inline functions. These should be
Peter Kasting5e04bd32019-05-21 21:44:10106named using `snake_case()`. Virtual functions should never be declared this way.
brettwf0e606a52016-07-06 21:17:20107
108## Logging
109
110Remove most logging calls before checking in. Unless you're adding temporary
111logging to track down a specific bug, and you have a plan for how to collect
112the logged data from user machines, you should generally not add logging
113statements.
114
115For the rare case when logging needs to stay in the codebase for a while,
116prefer `DVLOG(1)` to other logging methods. This avoids bloating the release
117executable and in debug can be selectively enabled at runtime by command-line
118arguments:
Peter Kasting5e04bd32019-05-21 21:44:10119 * `--v=n` sets the global log level to n (default 0). All log statements with
120 a log level less than or equal to the global level will be printed.
brettwf0e606a52016-07-06 21:17:20121 * `--vmodule=mod=n[,mod=n,...]` overrides the global log level for the module
122 mod. Supplying the string foo for mod will affect all files named foo.cc,
123 while supplying a wildcard like `*bar/baz*` will affect all files with
124 `bar/baz` in their full pathnames.
125
126## Platform-specific code
127
128To `#ifdef` code for specific platforms, use the macros defined in
129`build/build_config.h` and in the Chromium build config files, not other macros
Tommy C. Li1a13764a2018-09-17 21:18:34130set by specific compilers or build environments (e.g. `WIN32`).
brettwf0e606a52016-07-06 21:17:20131
132Place platform-specific #includes in their own section below the "normal"
133`#includes`. Repeat the standard `#include` order within this section:
134
135```c++
136 #include "foo/foo.h"
137
138 #include <stdint.h>
139 #include <algorithm>
140
141 #include "base/strings/utf_string_conversions.h"
Xiaohan Wang0727d882022-01-21 03:03:43142 #include "build/build_config.h"
brettwf0e606a52016-07-06 21:17:20143 #include "chrome/common/render_messages.h"
144
Xiaohan Wang0727d882022-01-21 03:03:43145 #if BUILDFLAG(IS_WIN)
brettwf0e606a52016-07-06 21:17:20146 #include <windows.h>
Robert Liaoc7c9a1c2017-10-18 01:41:31147 #include "base/win/com_init_util.h"
Xiaohan Wang0727d882022-01-21 03:03:43148 #elif BUILDFLAG(IS_POSIX)
brettwf0e606a52016-07-06 21:17:20149 #include "base/posix/global_descriptors.h"
150 #endif
151```
152
153## Types
154
Dominick Ng71a699a2022-01-26 23:46:57155 * Refer to the [Mojo style
156 guide](https://chromium.googlesource.com/chromium/src/+/main/docs/security/mojo.md)
157 when working with types that will be passed across network or process
158 boundaries. For example, explicitly-sized integral types must be used for
159 safety, since the sending and receiving ends may not have been compiled
160 with the same sizes for things like `int` and `size_t`.
brettwf0e606a52016-07-06 21:17:20161 * Use `size_t` for object and allocation sizes, object counts, array and
Peter Kasting5e04bd32019-05-21 21:44:10162 pointer offsets, vector indices, and so on. This prevents casts when
163 dealing with STL APIs, and if followed consistently across the codebase,
164 minimizes casts elsewhere.
165 * Occasionally classes may have a good reason to use a type other than
166 `size_t` for one of these concepts, e.g. as a storage space optimization. In
167 these cases, continue to use `size_t` in public-facing function
168 declarations, and continue to use unsigned types internally (e.g.
169 `uint32_t`).
Dominick Ng71a699a2022-01-26 23:46:57170 * Follow the [integer semantics
171 guide](https://chromium.googlesource.com/chromium/src/+/main/docs/security/integer-semantics.md)
172 for all arithmetic conversions and calculations used in memory management
173 or passed across network or process boundaries. In other circumstances,
174 follow [Google C++ casting
Dana Fried74a18892018-09-13 19:10:01175 conventions](https://google.github.io/styleguide/cppguide.html#Casting)
176 to convert arithmetic types when you know the conversion is safe. Use
Chris Palmer8218b8572019-02-26 00:19:16177 `checked_cast<T>` (from `base/numerics/safe_conversions.h`) when you need to
178 `CHECK` that the source value is in range for the destination type. Use
179 `saturated_cast<T>` if you instead wish to clamp out-of-range values.
Peter Kasting5e04bd32019-05-21 21:44:10180 `CheckedNumeric` is an ergonomic way to perform safe arithmetic and casting
181 in many cases.
Peter Kasting9e210a522021-03-20 15:45:42182 * The Google Style Guide [bans
183 UTF-16](https://google.github.io/styleguide/cppguide.html#Non-ASCII_Characters).
184 For various reasons, Chromium uses UTF-16 extensively. Use `std::u16string`
185 and `char16_t*` for 16-bit strings, `u"..."` to declare UTF-16 literals, and
186 either the actual characters or the `\uXXXX` or `\UXXXXXXXX` escapes for
187 Unicode characters. Avoid `\xXX...`-style escapes, which can cause subtle
188 problems if someone attempts to change the type of string that holds the
189 literal. In code used only on Windows, it may be necessary to use
190 `std::wstring` and `wchar_t*`; these are legal, but note that they are
191 distinct types and are often not 16-bit on other platforms.
brettwf0e606a52016-07-06 21:17:20192
193## Object ownership and calling conventions
194
195When functions need to take raw or smart pointers as parameters, use the
196following conventions. Here we refer to the parameter type as `T` and name as
197`t`.
Peter Kasting5e04bd32019-05-21 21:44:10198 * If the function does not modify `t`'s ownership, declare the param as `T*`.
199 The caller is expected to ensure `t` stays alive as long as necessary,
200 generally through the duration of the call. Exception: In rare cases (e.g.
201 using lambdas with STL algorithms over containers of `unique_ptr<>`s), you
202 may be forced to declare the param as `const std::unique_ptr<T>&`. Do this
203 only when required.
brettwf0e606a52016-07-06 21:17:20204 * If the function takes ownership of a non-refcounted object, declare the
205 param as `std::unique_ptr<T>`.
brettwf0e606a52016-07-06 21:17:20206 * If the function (at least sometimes) takes a ref on a refcounted object,
207 declare the param as `scoped_refptr<T>`. The caller can decide
208 whether it wishes to transfer ownership (by calling `std::move(t)` when
209 passing `t`) or retain its ref (by simply passing t directly).
brettwf0e606a52016-07-06 21:17:20210 * In short, functions should never take ownership of parameters passed as raw
211 pointers, and there should rarely be a need to pass smart pointers by const
212 ref.
213
Gabriel Charetteb62806f4a2019-01-29 21:08:41214Conventions for return values are similar with an important distinction:
215 * Return raw pointers if-and-only-if the caller does not take ownership.
216 * Return `std::unique_ptr<T>` or `scoped_refptr<T>` by value when the impl is
217 handing off ownership.
218 * **Distinction**: Return `const scoped_refptr<T>&` when the impl retains
219 ownership so the caller isn't required to take a ref: this avoids bumping
220 the reference count if the caller doesn't need ownership and also
221 [helps binary size](https://crrev.com/c/1435627)).
brettwf0e606a52016-07-06 21:17:20222
223A great deal of Chromium code predates the above rules. In particular, some
224functions take ownership of params passed as `T*`, or take `const
225scoped_refptr<T>&` instead of `T*`, or return `T*` instead of
226`scoped_refptr<T>` (to avoid refcount churn pre-C++11). Try to clean up such
227code when you find it, or at least not make such usage any more widespread.
228
Lukasz Anforowicz269e41d2021-11-30 18:32:01229## Non-owning pointers in class fields
230
danakj2c782052022-06-30 02:13:48231Use `const raw_ref<T>` or `raw_ptr<T>` for class and struct fields in place of a
232raw C++ reference `T&` or pointer `T*` whenever possible, except in paths that include
233`/renderer/` or `blink/public/web/`. These a non-owning smart pointers that
234have improved memory-safety over raw pointers and references, and can prevent
235exploitation of a significant percentage of Use-after-Free bugs.
Lukasz Anforowicz269e41d2021-11-30 18:32:01236
danakj2c782052022-06-30 02:13:48237Prefer `const raw_ref<T>` whenever the held pointer will never be null, and it's
238ok to drop the `const` if the internal reference can be reassigned to point to a
239different `T`. Use `raw_ptr<T>` in order to express that the pointer _can_ be
240null. Only `raw_ptr<T>` can be default-constructed, since `raw_ref<T>` disallows
241nullness.
242
243Using `raw_ref<T>` or `raw_ptr<T>` may not be possible in rare cases for
244[performance reasons](../../base/memory/raw_ptr.md#Performance). Additionally,
245`raw_ptr<T>` doesn’t support some C++ scenarios (e.g. `constexpr`, ObjC
246pointers). Tooling will help to encourage use of these types in the future. See
247[raw_ptr.md](../../base/memory/raw_ptr.md#When-to-use-raw_ptr_T) for how to add
248exclusions.
Lukasz Anforowicz269e41d2021-11-30 18:32:01249
brettwf0e606a52016-07-06 21:17:20250## Forward declarations vs. #includes
251
252Unlike the Google style guide, Chromium style prefers forward declarations to
253`#includes` where possible. This can reduce compile times and result in fewer
254files needing recompilation when a header changes.
255
256You can and should use forward declarations for most types passed or returned
257by value, reference, or pointer, or types stored as pointer members or in most
258STL containers. However, if it would otherwise make sense to use a type as a
259member by-value, don't convert it to a pointer just to be able to
260forward-declare the type.
261
262## File headers
263
Peter Kasting5e04bd32019-05-21 21:44:10264All files in Chromium start with a common license header. That header should
265look like this:
brettwf0e606a52016-07-06 21:17:20266
267```c++
268// Copyright $YEAR The Chromium Authors. All rights reserved.
269// Use of this source code is governed by a BSD-style license that can be
270// found in the LICENSE file.
271```
272
273Some important notes about this header:
brettwf0e606a52016-07-06 21:17:20274 * There is no `(c)` after `Copyright`.
Peter Kasting5e04bd32019-05-21 21:44:10275 * `$YEAR` should be set to the current year at the time a file is created, and
276 not changed thereafter.
277 * For files specific to Chromium OS, replace the word Chromium with the phrase
278 Chromium OS.
brettwf0e606a52016-07-06 21:17:20279 * If the style changes, don't bother to update existing files to comply with
280 the new style. For the same reason, don't just blindly copy an existing
281 file's header when creating a new file, since the existing file may use an
282 outdated style.
brettwf0e606a52016-07-06 21:17:20283 * The Chromium project hosts mirrors of some upstream open-source projects.
284 When contributing to these portions of the repository, retain the existing
285 file headers.
286
287Use standard `#include` guards in all header files (see the Google style guide
288sections on these for the naming convention). Do not use `#pragma once`;
289historically it was not supported on all platforms, and it does not seem to
290outperform #include guards even on platforms which do support it.
291
292## CHECK(), DCHECK(), and NOTREACHED()
293
294The `CHECK()` macro will cause an immediate crash if its condition is not met.
295`DCHECK()` is like `CHECK()` but is only compiled in when `DCHECK_IS_ON` is true
296(debug builds and some bot configurations, but not end-user builds).
297`NOTREACHED()` is equivalent to `DCHECK(false)`. Here are some rules for using
298these:
brettwf0e606a52016-07-06 21:17:20299 * Use `DCHECK()` or `NOTREACHED()` as assertions, e.g. to document pre- and
300 post-conditions. A `DCHECK()` means "this condition must always be true",
301 not "this condition is normally true, but perhaps not in exceptional
302 cases." Things like disk corruption or strange network errors are examples
303 of exceptional circumstances that nevertheless should not result in
304 `DCHECK()` failure.
brettwf0e606a52016-07-06 21:17:20305 * A consequence of this is that you should not handle DCHECK() failures, even
Peter Kasting5e04bd32019-05-21 21:44:10306 if failure would result in a crash. Attempting to handle a `DCHECK()`
307 failure is a statement that the `DCHECK()` can fail, which contradicts the
308 point of writing the `DCHECK()`. In particular, do not write code like the
309 following:
brettwf0e606a52016-07-06 21:17:20310 ```c++
311 DCHECK(foo);
Peter Kasting5e04bd32019-05-21 21:44:10312 if (!foo) // Eliminate this code.
313 ...
brettwf0e606a52016-07-06 21:17:20314
Peter Kasting5e04bd32019-05-21 21:44:10315 if (!bar) { // Replace this whole conditional with "DCHECK(bar);".
brettwf0e606a52016-07-06 21:17:20316 NOTREACHED();
Peter Kasting5e04bd32019-05-21 21:44:10317 return;
brettwf0e606a52016-07-06 21:17:20318 }
319 ```
brettwf0e606a52016-07-06 21:17:20320 * Use `CHECK()` if the consequence of a failed assertion would be a security
321 vulnerability, where crashing the browser is preferable. Because this takes
322 down the whole browser, sometimes there are better options than `CHECK()`.
323 For example, if a renderer sends the browser process a malformed IPC, an
324 attacker may control the renderer, but we can simply kill the offending
325 renderer instead of crashing the whole browser.
brettwf0e606a52016-07-06 21:17:20326 * You can temporarily use `CHECK()` instead of `DCHECK()` when trying to
327 force crashes in release builds to sniff out which of your assertions is
328 failing. Don't leave these in the codebase forever; remove them or change
329 them back once you've solved the problem.
brettwf0e606a52016-07-06 21:17:20330 * Don't use these macros in tests, as they crash the test binary and leave
331 bots in a bad state. Use the `ASSERT_xx()` and `EXPECT_xx()` family of
332 macros, which report failures gracefully and can continue running other
333 tests.
danakjcd463f12021-02-12 19:53:13334 * Dereferencing a null pointer in C++ is generally UB (undefined behavior) as
335 the compiler is free to assume a dereference means the pointer is not null
336 and may apply optimizations based on that. As such, there is sometimes a
337 strong opinion to `CHECK()` pointers before dereference. Chromium builds
338 with the `no-delete-null-pointer-checks` Clang/GCC flag which prevents such
339 optimizations, meaning the side effect of a null dereference would just be
340 the use of 0x0 which will lead to a crash on all the platforms Chromium
341 supports. As such we do not use `CHECK()` to guard pointer deferences. A
342 `DCHECK()` can be used to document that a pointer is never null, and doing
343 so as early as possible can help with debugging, though our styleguide now
344 recommends using a reference instead of a pointer when it cannot be null.
brettwf0e606a52016-07-06 21:17:20345
Roland Bockd662a2d2022-07-12 20:55:27346## Test-only code paths in production code
347
348Try to avoid test-only code paths in production code. Such code paths make
349production code behave differently in tests. This makes both tests and
350production code hard to reason about. Consider dependency injection, fake
351classes, etc to avoid such code paths.
352
353However, if a test-only path in production code cannot be avoided, instrument
354that code path with `CHECK_IS_TEST();` to assert that the code is only run in
355tests.
356
357```c++
358// `profile_manager` may not be available in tests.
359if (!profile_manager) {
360 CHECK_IS_TEST();
361 return std::string();
362}
363```
364
365`CHECK_IS_TEST();` will crash outside of tests. This asserts that the test-only
366code path is not accidentally or maliciously taken in production.
367
brettwf0e606a52016-07-06 21:17:20368## Miscellany
369
370 * Use UTF-8 file encodings and LF line endings.
brettwf0e606a52016-07-06 21:17:20371 * Unit tests and performance tests should be placed in the same directory as
372 the functionality they're testing.
Xiaohan Wangcc517f082019-01-16 01:58:14373 * The [C++ Dos and Don'ts](c++-dos-and-donts.md) page has more helpful
374 information.