3 ===========================
4 Style Guide and Conventions
5 ===========================
8 Pigweed runs ``pw format`` as part of ``pw presubmit`` to perform some code
9 formatting checks. To speed up the review process, consider adding ``pw
10 presubmit`` as a git push hook using the following command:
11 ``pw presubmit --install``
17 The Pigweed C++ style guide is closely based on Google's external C++ Style
18 Guide, which is found on the web at
19 https://google.github.io/styleguide/cppguide.html. The Google C++ Style Guide
20 applies to Pigweed except as described in this document.
22 The Pigweed style guide only applies to Pigweed itself. It does not apply to
23 projects that use Pigweed or to the third-party code included with Pigweed.
24 Non-Pigweed code is free to use features restricted by Pigweed, such as dynamic
25 memory allocation and the entirety of the C++ Standard Library.
27 Recommendations in the :doc:`embedded_cpp_guide` are considered part of the
28 Pigweed style guide, but are separated out since it covers more general
29 embedded development beyond just C++ style.
33 Pigweed uses `clang-format <https://clang.llvm.org/docs/ClangFormat.html>`_ to
34 automatically format Pigweed source code. A ``.clang-format`` configuration is
35 provided with the Pigweed repository.
37 Automatic formatting is essential to facilitate large-scale, automated changes
38 in Pigweed. Therefore, all code in Pigweed is expected to be formatted with
39 ``clang-format`` prior to submission. Existing code may be reformatted at any
42 If ``clang-format`` formats code in an undesirable or incorrect way, it can be
43 disabled for the affected lines by adding ``// clang-format off``.
44 ``clang-format`` must then be re-enabled with a ``// clang-format on`` comment.
49 constexpr int kMyMatrix[] = {
58 In C++ headers, always use the C++ versions of C Standard Library headers (e.g.
59 ``<cstdlib>`` instead of ``<stdlib.h>``). If the header is used by both C and
60 C++ code, only the C header should be used.
62 In C++ code, it is preferred to use C functions from the ``std`` namespace. For
63 example, use ``std::memcpy`` instead of ``memcpy``. The C++ standard does not
64 require the global namespace versions of the functions to be provided. Using
65 ``std::`` is more consistent with the C++ Standard Library and makes it easier
66 to distinguish Pigweed functions from library functions.
68 Within core Pigweed, do not use C standard library functions that allocate
69 memory, such as ``std::malloc``. There are exceptions to this for when dynamic
70 allocation is enabled for a system; Pigweed modules are allowed to add extra
71 functionality when a heap is present; but this must be optional.
75 Much of the C++ Standard Library is not a good fit for embedded software. Many
76 of the classes and functions were not designed with the RAM, flash, and
77 performance constraints of a microcontroller in mind. For example, simply
78 adding the line ``#include <iostream>`` can increase the binary size by 150 KB!
79 This is larger than many microcontrollers' entire internal storage.
81 However, with appropriate caution, a limited set of standard C++ libraries can
82 be used to great effect. Developers can leverage familiar, well-tested
83 abstractions instead of writing their own. C++ library algorithms and classes
84 can give equivalent or better performance than hand-written C code.
86 A limited subset of the C++ Standard Library is permitted in Pigweed. To keep
87 Pigweed small, flexible, and portable, functions that allocate dynamic memory
88 must be avoided. Care must be exercised when using multiple instantiations of a
89 template function, which can lead to code bloat.
91 The following C++ Standard Library headers are always permitted:
95 * ``<initializer_list>``
107 * C Standard Library headers (``<c*>``)
109 With caution, parts of the following headers can be used:
111 * ``<algorithm>`` -- be wary of potential memory allocation
112 * ``<atomic>`` -- not all MCUs natively support atomic operations
113 * ``<bitset>`` -- conversions to or from strings are disallowed
114 * ``<functional>`` -- do **not** use ``std::function``
115 * ``<new>`` -- for placement new
116 * ``<numeric>`` -- be wary of code size with multiple template instantiations
118 Never use any of these headers:
120 * Dynamic containers (``<list>``, ``<map>``, ``<set>``, ``<vector>``, etc.)
121 * Streams (``<iostream>``, ``<ostream>``, ``<fstream>``, etc.)
123 * ``<future>``, ``<mutex>``, ``<thread>``
126 * ``<scoped_allocator>``
132 Headers not listed here should be carefully evaluated before they are used.
134 These restrictions do not apply to third party code or to projects that use
139 Prefer to write C++ code over C code, using ``extern "C"`` for symbols that must
140 have C linkage. ``extern "C"`` functions should be defined within C++
141 namespaces to simplify referring to other code.
143 C++ functions with no parameters do not include ``void`` in the parameter list.
144 C functions with no parameters must include ``void``.
150 bool ThisIsACppFunction() { return true; }
152 extern "C" int pw_ThisIsACFunction(void) { return -1; }
156 int pw_ThisIsAlsoACFunction(void) {
157 return ThisIsACppFunction() ? 100 : 0;
166 Prefer C++-style (``//``) comments over C-style commments (``/* */``). C-style
167 comments should only be used for inline comments.
171 // Use C++-style comments, except where C-style comments are necessary.
172 // This returns a random number using an algorithm I found on the internet.
173 #define RANDOM_NUMBER() [] { \
174 return 4; /* chosen by fair dice roll */ \
177 Indent code in comments with two additional spaces, making a total of three
178 spaces after the ``//``. All code blocks must begin and end with an empty
179 comment line, even if the blank comment line is the last line in the block.
183 // Here is an example of code in comments.
185 // int indentation_spaces = 2;
186 // int total_spaces = 3;
188 // engine_1.thrust = RANDOM_NUMBER() * indentation_spaces + total_spaces;
194 All loops and conditional statements must use braces.
196 The syntax ``while (true)`` is preferred over ``for (;;)`` for infinite loops.
200 The first non-comment line of every header file must be ``#pragma once``. Do
201 not use traditional macro include guards. The ``#pragma once`` should come
202 directly after the Pigweed copyright block, with no blank line, followed by a
207 // Copyright 2020 The Pigweed Authors
209 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
210 // use this file except in compliance with the License. You may obtain a copy of
213 // https://www.apache.org/licenses/LICENSE-2.0
215 // Unless required by applicable law or agreed to in writing, software
216 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
217 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
218 // License for the specific language governing permissions and limitations under
222 // Header file-level comment goes here...
226 Dynamic memory allocation can be problematic. Heap allocations and deallocations
227 occupy valuable CPU cycles. Memory usage becomes nondeterministic, which can
228 result in a system crashing without a clear culprit.
230 To keep Pigweed portable, core Pigweed code is not permitted to dynamically
231 (heap) allocate memory, such as with ``malloc`` or ``new``. All memory should be
232 allocated with automatic (stack) or static (global) storage duration. Pigweed
233 must not use C++ libraries that use dynamic allocation.
235 Projects that use Pigweed are free to use dynamic allocation, provided they
236 have selected a target that enables the heap.
240 Entities shall be named according to the `Google style guide
241 <https://google.github.io/styleguide/cppguide.html>`_, with the following
242 additional requirements.
245 * All Pigweed C++ code must be in the ``pw`` namespace. Namespaces for
246 modules should be nested under ``pw``. For example,
247 ``pw::string::Format()``.
248 * Whenever possible, private code should be in a source (.cc) file and placed
249 in anonymous namespace nested under ``pw``.
250 * If private code must be exposed in a header file, it must be in a namespace
251 nested under ``pw``. The namespace may be named for its subsystem or use a
252 name that designates it as private, such as ``internal``.
253 * Template arguments for non-type names (e.g. ``template <int foo_bar>``)
254 should follow the variable naming convention, which means snake case (e.g.
255 ``foo_bar``). This matches the Google C++ style, however the wording in the
256 official style guide isn't explicit and could be interpreted to use
257 ``kFooBar`` style naming. Wide practice establishes that the naming
258 convention is ``snake_case``, and so that is the style we use in Pigweed.
260 **Note:** At time of writing much of Pigweed incorrectly follows the
261 ``kCamelCase`` naming for non-type template arguments. This is a bug that
262 will be fixed eventually.
265 In general, C symbols should be prefixed with the module name. If the symbol is
266 not associated with a module, use just ``pw`` as the module name. Facade
267 backends may chose to prefix symbols with the facade's name to help reduce the
268 length of the prefix.
270 * Public names used by C code must be prefixed with the module name (e.g.
272 * If private code must be exposed in a header, private names used by C code
273 must be prefixed with an underscore followed by the module name (e.g.
275 * Avoid writing C source (.c) files in Pigweed. Prefer to write C++ code with
276 C linkage using ``extern "C"``. Within C source, private C functions and
277 variables must be named with the ``_pw_my_module_*`` prefix and should be
278 declared ``static`` whenever possible; for example,
279 ``_pw_my_module_MyPrivateFunction``.
280 * The C prefix rules apply to
282 * C functions (``int pw_foo_FunctionName(void);``),
283 * variables used by C code (``int pw_foo_variable_name;``),
284 * constant variables used by C code (``int pw_foo_kConstantName;``),
285 * structs used by C code (``typedef struct {} pw_foo_StructName;``), and
286 * all of the above for ``extern "C"`` names in C++ code.
288 The prefix does not apply to struct members, which use normal Google style.
290 **Preprocessor macros**
291 * Public Pigweed macros must be prefixed with the module name (e.g.
293 * Private Pigweed macros must be prefixed with an underscore followed by the
294 module name (e.g. ``_PW_MY_MODULE_*``).
300 namespace pw::my_module {
301 namespace nested_namespace {
303 // C++ names (types, variables, functions) must be in the pw namespace.
304 // They are named according to the Google style guide.
305 constexpr int kGlobalConstant = 123;
307 // Prefer using functions over extern global variables.
308 extern int global_variable;
316 // Public Pigweed code used from C must be prefixed with pw_.
317 extern const int pw_my_module_kGlobalConstant;
319 extern int pw_my_module_global_variable;
321 void pw_my_module_Function(void);
325 } pw_my_module_Struct;
327 // Private Pigweed code used from C must be prefixed with _pw_.
328 extern const int _pw_my_module_kPrivateGlobalConstant;
330 extern int _pw_my_module_private_global_variable;
332 void _pw_my_module_PrivateFunction(void);
336 } _pw_my_module_PrivateStruct;
340 // Public macros must be prefixed with PW_.
341 #define PW_MY_MODULE_PUBLIC_MACRO(arg) arg
343 // Private macros must be prefixed with _PW_.
344 #define _PW_MY_MODULE_PRIVATE_MACRO(arg) arg
346 } // namespace nested_namespace
347 } // namespace pw::my_module
349 Namespace scope formatting
350 ==========================
351 All non-indented blocks (namespaces, ``extern "C"`` blocks, and preprocessor
352 conditionals) must have a comment on their closing line with the
353 contents of the starting line.
355 All nested namespaces should be declared together with no blank lines between
360 #include "some/header.h"
362 namespace pw::nested {
365 constexpr int kAnonConstantGoesHere = 0;
371 const char* SomeClass::yes = "no";
373 bool ThisIsAFunction() {
378 #endif // PW_CONFIG_IS_SET
383 const int pw_kSomeConstant = 10;
384 int pw_some_global_variable = 600;
386 void pw_CFunction() { ... }
391 } // namespace pw::nested
393 Pointers and references
394 =======================
395 For pointer and reference types, place the asterisk or ampersand next to the
400 int* const number = &that_thing;
401 constexpr const char* kString = "theory!"
403 bool FindTheOneRing(const Region& where_to_look) { ... }
405 Prefer storing references over storing pointers. Pointers are required when the
406 pointer can change its target or may be ``nullptr``. Otherwise, a reference or
407 const reference should be used. In accordance with the Google C++ style guide,
408 only const references are permitted as function arguments; pointers must be used
409 in place of mutable references when passed as function arguments.
413 Macros should only be used when they significantly improve upon the C++ code
414 they replace. Macros should make code more readable, robust, and safe, or
415 provide features not possible with standard C++, such as stringification, line
416 number capturing, or conditional compilation. When possible, use C++ constructs
417 like constexpr variables in place of macros. Never use macros as constants,
418 except when a string literal is needed or the value must be used by C code.
420 When macros are needed, the macros should be accompanied with extensive tests
421 to ensure the macros are hard to use wrong.
423 Stand-alone statement macros
424 ----------------------------
425 Macros that are standalone statements must require the caller to terminate the
426 macro invocation with a semicolon. For example, the following does *not* conform
427 to Pigweed's macro style:
431 // BAD! Definition has built-in semicolon.
432 #define PW_LOG_IF_BAD(mj) \
433 CallSomeFunction(mj);
435 // BAD! Compiles without error; semicolon is missing.
438 Here's how to do this instead:
442 // GOOD; requires semicolon to compile.
443 #define PW_LOG_IF_BAD(mj) \
446 // GOOD; fails to compile due to lacking semicolon.
449 For macros in function scope that do not already require a semicolon, the
450 contents can be placed in a ``do { ... } while (0)`` loop.
454 #define PW_LOG_IF_BAD(mj) \
461 Standalone macros at global scope that do not already require a semicolon can
462 add a ``static_assert`` or throwaway struct declaration statement as their
467 #define PW_NEAT_THING(thing) \
468 bool IsNeat_##thing() { return true; } \
469 static_assert(true, "Macros must be terminated with a semicolon")
471 Private macros in public headers
472 --------------------------------
473 Private macros in public headers must be prefixed with ``_PW_``, even if they
474 are undefined after use; this prevents collisions with downstream users. For
479 #define _PW_MY_SPECIAL_MACRO(op) ...
481 // Code that uses _PW_MY_SPECIAL_MACRO()
483 #undef _PW_MY_SPECIAL_MACRO
485 Macros in private implementation files (.cc)
486 --------------------------------------------
487 Macros within .cc files that should only used within one file should be
488 undefined after their last use; for example:
492 #define DEFINE_OPERATOR(op) \
493 T operator ## op(T x, T y) { return x op y; } \
494 static_assert(true, "Macros must be terminated with a semicolon") \
501 #undef DEFINE_OPERATOR
503 Preprocessor conditional statements
504 ===================================
505 When using macros for conditional compilation, prefer to use ``#if`` over
506 ``#ifdef``. This checks the value of the macro rather than whether it exists.
508 * ``#if`` handles undefined macros equivalently to ``#ifdef``. Undefined
509 macros expand to 0 in preprocessor conditional statements.
510 * ``#if`` evaluates false for macros defined as 0, while ``#ifdef`` evaluates
512 * Macros defined using compiler flags have a default value of 1 in GCC and
513 Clang, so they work equivalently for ``#if`` and ``#ifdef``.
514 * Macros defined to an empty statement cause compile-time errors in ``#if``
515 statements, which avoids ambiguity about how the macro should be used.
517 All ``#endif`` statements should be commented with the expression from their
518 corresponding ``#if``. Do not indent within preprocessor conditional statements.
523 using Word = uint64_t;
525 using Word = uint32_t;
526 #endif // USE_64_BIT_WORD
530 Unsigned integers are permitted in Pigweed. Aim for consistency with existing
531 code and the C++ Standard Library. Be very careful mixing signed and unsigned
537 Pigweed uses the standard Python style: PEP8, which is available on the web at
538 https://www.python.org/dev/peps/pep-0008/. All Pigweed Python code should pass
539 ``yapf`` when configured for PEP8 style.
543 Pigweed uses Python 3. Some modules may offer limited support for Python 2, but
544 Python 3.6 or newer is required for most Pigweed code.
550 Each Pigweed source module will require a build file named BUILD.gn which
551 encapsulates the build targets and specifies their sources and dependencies.
552 The format of this file is simlar in structure to the
553 `Bazel/Blaze format <https://docs.bazel.build/versions/3.2.0/build-ref.html>`_
554 (Googlers may also review `go/build-style <go/build-style>`_), but with
555 nomenclature specific to Pigweed. For each target specified within the build
556 file there are a list of depdency fields. Those fields, in their expected
559 * ``<public_config>`` -- external build configuration
560 * ``<public_deps>`` -- necessary public dependencies (ie: Pigweed headers)
561 * ``<public>`` -- exposed package public interface header files
562 * ``<config>`` -- package build configuration
563 * ``<sources>`` -- package source code
564 * ``<deps>`` -- package necessary local dependencies
566 Assets within each field must be listed in alphabetical order
570 # Here is a brief example of a GN build file.
572 import("$dir_pw_unit_test/test.gni")
574 config("default_config") {
575 include_dirs = [ "public" ]
578 source_set("pw_sample_module") {
579 public_configs = [ ":default_config" ]
580 public_deps = [ dir_pw_status ]
581 public = [ "public/pw_sample_module/sample_module.h" ]
583 "public/pw_sample_module/internal/sample_module.h",
585 "used_by_sample_module.cc",
587 deps = [ dir_pw_varint ]
590 pw_test_group("tests") {
591 tests = [ ":sample_module_test" ]
594 pw_test("sample_module_test") {
595 sources = [ "sample_module_test.cc" ]
596 deps = [ ":sample_module" ]
599 pw_doc_group("docs") {
600 sources = [ "docs.rst" ]