1*61c4878aSAndroid Build Coastguard Worker.. _docs-pw-style-cpp: 2*61c4878aSAndroid Build Coastguard Worker 3*61c4878aSAndroid Build Coastguard Worker========= 4*61c4878aSAndroid Build Coastguard WorkerC++ style 5*61c4878aSAndroid Build Coastguard Worker========= 6*61c4878aSAndroid Build Coastguard WorkerThe Pigweed C++ style guide is closely based on Google's external C++ Style 7*61c4878aSAndroid Build Coastguard WorkerGuide, which is found on the web at 8*61c4878aSAndroid Build Coastguard Workerhttps://google.github.io/styleguide/cppguide.html. The Google C++ Style Guide 9*61c4878aSAndroid Build Coastguard Workerapplies to Pigweed except as described in this document. 10*61c4878aSAndroid Build Coastguard Worker 11*61c4878aSAndroid Build Coastguard WorkerThe Pigweed style guide only applies to Pigweed itself. It does not apply to 12*61c4878aSAndroid Build Coastguard Workerprojects that use Pigweed or to the third-party code included with Pigweed. 13*61c4878aSAndroid Build Coastguard WorkerNon-Pigweed code is free to use features restricted by Pigweed, such as dynamic 14*61c4878aSAndroid Build Coastguard Workermemory allocation and the entirety of the C++ Standard Library. 15*61c4878aSAndroid Build Coastguard Worker 16*61c4878aSAndroid Build Coastguard WorkerRecommendations in the :ref:`docs-embedded-cpp` are considered part of the 17*61c4878aSAndroid Build Coastguard WorkerPigweed style guide, but are separated out since it covers more general 18*61c4878aSAndroid Build Coastguard Workerembedded development beyond just C++ style. 19*61c4878aSAndroid Build Coastguard Worker 20*61c4878aSAndroid Build Coastguard WorkerC++ standard 21*61c4878aSAndroid Build Coastguard Worker============ 22*61c4878aSAndroid Build Coastguard WorkerAll Pigweed C++ code must compile with ``-std=c++17`` in Clang and GCC. C++20 23*61c4878aSAndroid Build Coastguard Workerfeatures may be used as long as the code still compiles unmodified with C++17. 24*61c4878aSAndroid Build Coastguard WorkerSee ``pw_polyfill/language_feature_macros.h`` for macros that provide C++20 25*61c4878aSAndroid Build Coastguard Workerfeatures when supported. 26*61c4878aSAndroid Build Coastguard Worker 27*61c4878aSAndroid Build Coastguard WorkerCompiler extensions should not be used unless wrapped in a macro or properly 28*61c4878aSAndroid Build Coastguard Workerguarded in the preprocessor. See ``pw_processor/compiler.h`` for macros that 29*61c4878aSAndroid Build Coastguard Workerwrap compiler-specific features. 30*61c4878aSAndroid Build Coastguard Worker 31*61c4878aSAndroid Build Coastguard WorkerAutomatic formatting 32*61c4878aSAndroid Build Coastguard Worker==================== 33*61c4878aSAndroid Build Coastguard WorkerPigweed uses `clang-format <https://clang.llvm.org/docs/ClangFormat.html>`_ to 34*61c4878aSAndroid Build Coastguard Workerautomatically format Pigweed source code. A ``.clang-format`` configuration is 35*61c4878aSAndroid Build Coastguard Workerprovided with the Pigweed repository. Within an upstream Pigweed environment, the 36*61c4878aSAndroid Build Coastguard Worker`pw format` tool can be used to automatically format code. 37*61c4878aSAndroid Build Coastguard Worker 38*61c4878aSAndroid Build Coastguard WorkerAutomatic formatting is essential to facilitate large-scale, automated changes 39*61c4878aSAndroid Build Coastguard Workerin Pigweed. Therefore, all code in Pigweed is expected to be formatted with 40*61c4878aSAndroid Build Coastguard Worker``clang-format`` prior to submission. Existing code may be reformatted at any 41*61c4878aSAndroid Build Coastguard Workertime. 42*61c4878aSAndroid Build Coastguard Worker 43*61c4878aSAndroid Build Coastguard WorkerIf ``clang-format`` formats code in an undesirable or incorrect way, it can be 44*61c4878aSAndroid Build Coastguard Workerdisabled for the affected lines by adding ``// clang-format off``. 45*61c4878aSAndroid Build Coastguard Worker``clang-format`` must then be re-enabled with a ``// clang-format on`` comment. 46*61c4878aSAndroid Build Coastguard Worker 47*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 48*61c4878aSAndroid Build Coastguard Worker 49*61c4878aSAndroid Build Coastguard Worker // clang-format off 50*61c4878aSAndroid Build Coastguard Worker constexpr int kMyMatrix[] = { 51*61c4878aSAndroid Build Coastguard Worker 100, 23, 0, 52*61c4878aSAndroid Build Coastguard Worker 0, 542, 38, 53*61c4878aSAndroid Build Coastguard Worker 1, 2, 201, 54*61c4878aSAndroid Build Coastguard Worker }; 55*61c4878aSAndroid Build Coastguard Worker // clang-format on 56*61c4878aSAndroid Build Coastguard Worker 57*61c4878aSAndroid Build Coastguard WorkerC Standard Library 58*61c4878aSAndroid Build Coastguard Worker================== 59*61c4878aSAndroid Build Coastguard WorkerIn C++ headers, always use the C++ versions of C Standard Library headers (e.g. 60*61c4878aSAndroid Build Coastguard Worker``<cstdlib>`` instead of ``<stdlib.h>``). If the header is used by both C and 61*61c4878aSAndroid Build Coastguard WorkerC++ code, only the C header should be used. 62*61c4878aSAndroid Build Coastguard Worker 63*61c4878aSAndroid Build Coastguard WorkerIn C++ code, it is preferred to use C functions from the ``std`` namespace. For 64*61c4878aSAndroid Build Coastguard Workerexample, use ``std::memcpy`` instead of ``memcpy``. The C++ standard does not 65*61c4878aSAndroid Build Coastguard Workerrequire the global namespace versions of the functions to be provided. Using 66*61c4878aSAndroid Build Coastguard Worker``std::`` is more consistent with the C++ Standard Library and makes it easier 67*61c4878aSAndroid Build Coastguard Workerto distinguish Pigweed functions from library functions. 68*61c4878aSAndroid Build Coastguard Worker 69*61c4878aSAndroid Build Coastguard WorkerWithin core Pigweed, do not use C standard library functions that allocate 70*61c4878aSAndroid Build Coastguard Workermemory, such as ``std::malloc``. There are exceptions to this for when dynamic 71*61c4878aSAndroid Build Coastguard Workerallocation is enabled for a system; Pigweed modules are allowed to add extra 72*61c4878aSAndroid Build Coastguard Workerfunctionality when a heap is present; but this must be optional. 73*61c4878aSAndroid Build Coastguard Worker 74*61c4878aSAndroid Build Coastguard WorkerC++ Standard Library 75*61c4878aSAndroid Build Coastguard Worker==================== 76*61c4878aSAndroid Build Coastguard WorkerMuch of the C++ Standard Library is not a good fit for embedded software. Many 77*61c4878aSAndroid Build Coastguard Workerof the classes and functions were not designed with the RAM, flash, and 78*61c4878aSAndroid Build Coastguard Workerperformance constraints of a microcontroller in mind. For example, simply 79*61c4878aSAndroid Build Coastguard Workeradding the line ``#include <iostream>`` can increase the binary size by 150 KB! 80*61c4878aSAndroid Build Coastguard WorkerThis is larger than many microcontrollers' entire internal storage. 81*61c4878aSAndroid Build Coastguard Worker 82*61c4878aSAndroid Build Coastguard WorkerHowever, with appropriate caution, a limited set of standard C++ libraries can 83*61c4878aSAndroid Build Coastguard Workerbe used to great effect. Developers can leverage familiar, well-tested 84*61c4878aSAndroid Build Coastguard Workerabstractions instead of writing their own. C++ library algorithms and classes 85*61c4878aSAndroid Build Coastguard Workercan give equivalent or better performance than hand-written C code. 86*61c4878aSAndroid Build Coastguard Worker 87*61c4878aSAndroid Build Coastguard WorkerA limited subset of the C++ Standard Library is permitted in Pigweed. To keep 88*61c4878aSAndroid Build Coastguard WorkerPigweed small, flexible, and portable, functions that allocate dynamic memory 89*61c4878aSAndroid Build Coastguard Workermust be avoided. Care must be exercised when using multiple instantiations of a 90*61c4878aSAndroid Build Coastguard Workertemplate function, which can lead to code bloat. 91*61c4878aSAndroid Build Coastguard Worker 92*61c4878aSAndroid Build Coastguard WorkerPermitted Headers 93*61c4878aSAndroid Build Coastguard Worker----------------- 94*61c4878aSAndroid Build Coastguard Worker.. admonition:: The following C++ Standard Library headers are always permitted: 95*61c4878aSAndroid Build Coastguard Worker :class: checkmark 96*61c4878aSAndroid Build Coastguard Worker 97*61c4878aSAndroid Build Coastguard Worker * ``<array>`` 98*61c4878aSAndroid Build Coastguard Worker * ``<complex>`` 99*61c4878aSAndroid Build Coastguard Worker * ``<initializer_list>`` 100*61c4878aSAndroid Build Coastguard Worker * ``<iterator>`` 101*61c4878aSAndroid Build Coastguard Worker * ``<limits>`` 102*61c4878aSAndroid Build Coastguard Worker * ``<optional>`` 103*61c4878aSAndroid Build Coastguard Worker * ``<random>`` 104*61c4878aSAndroid Build Coastguard Worker * ``<ratio>`` 105*61c4878aSAndroid Build Coastguard Worker * ``<string_view>`` 106*61c4878aSAndroid Build Coastguard Worker * ``<tuple>`` 107*61c4878aSAndroid Build Coastguard Worker * ``<type_traits>`` 108*61c4878aSAndroid Build Coastguard Worker * ``<utility>`` 109*61c4878aSAndroid Build Coastguard Worker * ``<variant>`` 110*61c4878aSAndroid Build Coastguard Worker * C Standard Library headers (``<c*>``) 111*61c4878aSAndroid Build Coastguard Worker 112*61c4878aSAndroid Build Coastguard Worker.. admonition:: With caution, parts of the following headers can be used: 113*61c4878aSAndroid Build Coastguard Worker :class: warning 114*61c4878aSAndroid Build Coastguard Worker 115*61c4878aSAndroid Build Coastguard Worker * ``<algorithm>`` -- be wary of potential memory allocation 116*61c4878aSAndroid Build Coastguard Worker * ``<atomic>`` -- not all MCUs natively support atomic operations 117*61c4878aSAndroid Build Coastguard Worker * ``<bitset>`` -- conversions to or from strings are disallowed 118*61c4878aSAndroid Build Coastguard Worker * ``<functional>`` -- do **not** use ``std::function``; use 119*61c4878aSAndroid Build Coastguard Worker :ref:`module-pw_function` 120*61c4878aSAndroid Build Coastguard Worker * ``<mutex>`` -- can use ``std::lock_guard``, use :ref:`module-pw_sync` for 121*61c4878aSAndroid Build Coastguard Worker mutexes 122*61c4878aSAndroid Build Coastguard Worker * ``<new>`` -- for placement new 123*61c4878aSAndroid Build Coastguard Worker * ``<numeric>`` -- be wary of code size with multiple template instantiations 124*61c4878aSAndroid Build Coastguard Worker 125*61c4878aSAndroid Build Coastguard Worker.. admonition:: Never use any of these headers: 126*61c4878aSAndroid Build Coastguard Worker :class: error 127*61c4878aSAndroid Build Coastguard Worker 128*61c4878aSAndroid Build Coastguard Worker * Dynamic containers (``<list>``, ``<map>``, ``<set>``, ``<vector>``, etc.) 129*61c4878aSAndroid Build Coastguard Worker * Streams (``<iostream>``, ``<ostream>``, ``<fstream>``, ``<sstream>`` etc.) 130*61c4878aSAndroid Build Coastguard Worker -- in some cases :ref:`module-pw_stream` can work instead 131*61c4878aSAndroid Build Coastguard Worker * ``<span>`` -- use :ref:`module-pw_span` instead. Downstream projects may 132*61c4878aSAndroid Build Coastguard Worker want to directly use ``std::span`` if it is available, but upstream must 133*61c4878aSAndroid Build Coastguard Worker use the ``pw::span`` version for compatability 134*61c4878aSAndroid Build Coastguard Worker * ``<string>`` -- can use :ref:`module-pw_string` 135*61c4878aSAndroid Build Coastguard Worker * ``<thread>`` -- can use :ref:`module-pw_thread` 136*61c4878aSAndroid Build Coastguard Worker * ``<future>`` -- eventually :ref:`module-pw_async` will offer this 137*61c4878aSAndroid Build Coastguard Worker * ``<exception>``, ``<stdexcept>`` -- no exceptions 138*61c4878aSAndroid Build Coastguard Worker * ``<memory>``, ``<scoped_allocator>`` -- no allocations 139*61c4878aSAndroid Build Coastguard Worker * ``<regex>`` 140*61c4878aSAndroid Build Coastguard Worker * ``<valarray>`` 141*61c4878aSAndroid Build Coastguard Worker 142*61c4878aSAndroid Build Coastguard WorkerHeaders not listed here should be carefully evaluated before they are used. 143*61c4878aSAndroid Build Coastguard Worker 144*61c4878aSAndroid Build Coastguard WorkerThese restrictions do not apply to third party code or to projects that use 145*61c4878aSAndroid Build Coastguard WorkerPigweed. 146*61c4878aSAndroid Build Coastguard Worker 147*61c4878aSAndroid Build Coastguard WorkerCombining C and C++ 148*61c4878aSAndroid Build Coastguard Worker=================== 149*61c4878aSAndroid Build Coastguard WorkerPrefer to write C++ code over C code, using ``extern "C"`` for symbols that must 150*61c4878aSAndroid Build Coastguard Workerhave C linkage. ``extern "C"`` functions should be defined within C++ 151*61c4878aSAndroid Build Coastguard Workernamespaces to simplify referring to other code. 152*61c4878aSAndroid Build Coastguard Worker 153*61c4878aSAndroid Build Coastguard WorkerC++ functions with no parameters do not include ``void`` in the parameter list. 154*61c4878aSAndroid Build Coastguard WorkerC functions with no parameters must include ``void``. 155*61c4878aSAndroid Build Coastguard Worker 156*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 157*61c4878aSAndroid Build Coastguard Worker 158*61c4878aSAndroid Build Coastguard Worker namespace pw { 159*61c4878aSAndroid Build Coastguard Worker 160*61c4878aSAndroid Build Coastguard Worker bool ThisIsACppFunction() { return true; } 161*61c4878aSAndroid Build Coastguard Worker 162*61c4878aSAndroid Build Coastguard Worker extern "C" int pw_ThisIsACFunction(void) { return -1; } 163*61c4878aSAndroid Build Coastguard Worker 164*61c4878aSAndroid Build Coastguard Worker extern "C" { 165*61c4878aSAndroid Build Coastguard Worker 166*61c4878aSAndroid Build Coastguard Worker int pw_ThisIsAlsoACFunction(void) { 167*61c4878aSAndroid Build Coastguard Worker return ThisIsACppFunction() ? 100 : 0; 168*61c4878aSAndroid Build Coastguard Worker } 169*61c4878aSAndroid Build Coastguard Worker 170*61c4878aSAndroid Build Coastguard Worker } // extern "C" 171*61c4878aSAndroid Build Coastguard Worker 172*61c4878aSAndroid Build Coastguard Worker } // namespace pw 173*61c4878aSAndroid Build Coastguard Worker 174*61c4878aSAndroid Build Coastguard WorkerComments 175*61c4878aSAndroid Build Coastguard Worker======== 176*61c4878aSAndroid Build Coastguard WorkerPrefer C++-style (``//``) comments over C-style comments (``/* */``). C-style 177*61c4878aSAndroid Build Coastguard Workercomments should only be used for inline comments. 178*61c4878aSAndroid Build Coastguard Worker 179*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 180*61c4878aSAndroid Build Coastguard Worker 181*61c4878aSAndroid Build Coastguard Worker // Use C++-style comments, except where C-style comments are necessary. 182*61c4878aSAndroid Build Coastguard Worker // This returns a random number using an algorithm I found on the internet. 183*61c4878aSAndroid Build Coastguard Worker #define RANDOM_NUMBER() [] { \ 184*61c4878aSAndroid Build Coastguard Worker return 4; /* chosen by fair dice roll */ \ 185*61c4878aSAndroid Build Coastguard Worker }() 186*61c4878aSAndroid Build Coastguard Worker 187*61c4878aSAndroid Build Coastguard WorkerIndent code in comments with two additional spaces, making a total of three 188*61c4878aSAndroid Build Coastguard Workerspaces after the ``//``. All code blocks must begin and end with an empty 189*61c4878aSAndroid Build Coastguard Workercomment line, even if the blank comment line is the last line in the block. 190*61c4878aSAndroid Build Coastguard Worker 191*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 192*61c4878aSAndroid Build Coastguard Worker 193*61c4878aSAndroid Build Coastguard Worker // Here is an example of code in comments. 194*61c4878aSAndroid Build Coastguard Worker // 195*61c4878aSAndroid Build Coastguard Worker // int indentation_spaces = 2; 196*61c4878aSAndroid Build Coastguard Worker // int total_spaces = 3; 197*61c4878aSAndroid Build Coastguard Worker // 198*61c4878aSAndroid Build Coastguard Worker // engine_1.thrust = RANDOM_NUMBER() * indentation_spaces + total_spaces; 199*61c4878aSAndroid Build Coastguard Worker // 200*61c4878aSAndroid Build Coastguard Worker bool SomeFunction(); 201*61c4878aSAndroid Build Coastguard Worker 202*61c4878aSAndroid Build Coastguard WorkerPassing move-only or expensive-to-copy arguments 203*61c4878aSAndroid Build Coastguard Worker================================================ 204*61c4878aSAndroid Build Coastguard WorkerC++ offers a number of ways to pass arguments arguments to functions. 205*61c4878aSAndroid Build Coastguard WorkerWhen taking move-only or expensive-to-copy arguments, use the following table 206*61c4878aSAndroid Build Coastguard Workerto determine which argument type to use: 207*61c4878aSAndroid Build Coastguard Worker 208*61c4878aSAndroid Build Coastguard Worker.. list-table:: C++ argument type choices 209*61c4878aSAndroid Build Coastguard Worker :widths: 30 20 10 210*61c4878aSAndroid Build Coastguard Worker :header-rows: 1 211*61c4878aSAndroid Build Coastguard Worker 212*61c4878aSAndroid Build Coastguard Worker * - Use-case 213*61c4878aSAndroid Build Coastguard Worker - Name 214*61c4878aSAndroid Build Coastguard Worker - Syntax 215*61c4878aSAndroid Build Coastguard Worker * - If read-only 216*61c4878aSAndroid Build Coastguard Worker - By const reference 217*61c4878aSAndroid Build Coastguard Worker - ``const T&`` 218*61c4878aSAndroid Build Coastguard Worker * - If mutating 219*61c4878aSAndroid Build Coastguard Worker - By reference 220*61c4878aSAndroid Build Coastguard Worker - ``T&`` 221*61c4878aSAndroid Build Coastguard Worker * - If consuming 222*61c4878aSAndroid Build Coastguard Worker - By rvalue reference 223*61c4878aSAndroid Build Coastguard Worker - ``T&&`` 224*61c4878aSAndroid Build Coastguard Worker * - If conditionally consuming 225*61c4878aSAndroid Build Coastguard Worker - By value 226*61c4878aSAndroid Build Coastguard Worker - ``T`` 227*61c4878aSAndroid Build Coastguard Worker 228*61c4878aSAndroid Build Coastguard WorkerWhy rvalue references 229*61c4878aSAndroid Build Coastguard Worker--------------------- 230*61c4878aSAndroid Build Coastguard WorkerWhen a function consumes or moves such an argument, it should accept an rvalue 231*61c4878aSAndroid Build Coastguard Workerreference (``T&&``) rather than taking the argument by-value (``T``). An rvalue 232*61c4878aSAndroid Build Coastguard Workerreference forces the caller to ``std::move`` when passing a preexisting 233*61c4878aSAndroid Build Coastguard Workervariable, which makes the transfer of ownership explicit. 234*61c4878aSAndroid Build Coastguard Worker 235*61c4878aSAndroid Build Coastguard WorkerCompared with accepting arguments by-value, rvalue references prevent 236*61c4878aSAndroid Build Coastguard Workerunnecessary object instances and extra calls to move constructors. This has been 237*61c4878aSAndroid Build Coastguard Workershown to significantly impact code size and stack usage for Pigweed users. 238*61c4878aSAndroid Build Coastguard Worker 239*61c4878aSAndroid Build Coastguard WorkerThis is especially important when using ``pw::Function``. For more information 240*61c4878aSAndroid Build Coastguard Workerabout accepting ``pw::Function`` arguments, see 241*61c4878aSAndroid Build Coastguard Worker:ref:`module-pw_function-move-semantics`. 242*61c4878aSAndroid Build Coastguard Worker 243*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes**: Accept move-only or expensive-to-copy values by rvalue: 244*61c4878aSAndroid Build Coastguard Worker :class: checkmark 245*61c4878aSAndroid Build Coastguard Worker 246*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 247*61c4878aSAndroid Build Coastguard Worker 248*61c4878aSAndroid Build Coastguard Worker void FrobulateVector(pw::Vector<T>&& vector) { 249*61c4878aSAndroid Build Coastguard Worker Frobulate(std::move(vector)); 250*61c4878aSAndroid Build Coastguard Worker } 251*61c4878aSAndroid Build Coastguard Worker 252*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No**: Accepts move-only or expensive-to-copy values by value: 253*61c4878aSAndroid Build Coastguard Worker :class: error 254*61c4878aSAndroid Build Coastguard Worker 255*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 256*61c4878aSAndroid Build Coastguard Worker 257*61c4878aSAndroid Build Coastguard Worker void FrobulateVector(pw::Vector<T> vector) { 258*61c4878aSAndroid Build Coastguard Worker Frobulate(std::move(vector)); 259*61c4878aSAndroid Build Coastguard Worker } 260*61c4878aSAndroid Build Coastguard Worker 261*61c4878aSAndroid Build Coastguard WorkerThis guidance overrides the standard `Google style guidance on rvalues 262*61c4878aSAndroid Build Coastguard Worker<https://google.github.io/styleguide/cppguide.html#Rvalue_references>`_. 263*61c4878aSAndroid Build Coastguard Worker 264*61c4878aSAndroid Build Coastguard WorkerConditionally moving values 265*61c4878aSAndroid Build Coastguard Worker--------------------------- 266*61c4878aSAndroid Build Coastguard WorkerAn exception to the rule above is when a move-only or expensive-to-copy value 267*61c4878aSAndroid Build Coastguard Workeris only conditionally consumed by the body of the function, for example: 268*61c4878aSAndroid Build Coastguard Worker 269*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No**: Conditionally consumes ``vector``: 270*61c4878aSAndroid Build Coastguard Worker :class: error 271*61c4878aSAndroid Build Coastguard Worker 272*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 273*61c4878aSAndroid Build Coastguard Worker 274*61c4878aSAndroid Build Coastguard Worker void PossiblyFrobulate(bool should_frob, pw::Vector<T>&& vector) { 275*61c4878aSAndroid Build Coastguard Worker if (should_frob) { 276*61c4878aSAndroid Build Coastguard Worker Frobulate(std::move(vector)); 277*61c4878aSAndroid Build Coastguard Worker } 278*61c4878aSAndroid Build Coastguard Worker } 279*61c4878aSAndroid Build Coastguard Worker 280*61c4878aSAndroid Build Coastguard WorkerBecause ``PossiblyFrobulate`` above will only consume ``vector`` in some code 281*61c4878aSAndroid Build Coastguard Workerpaths, the original ``vector`` passed by the user will outlive the call to 282*61c4878aSAndroid Build Coastguard Worker``PossiblyFrobulate``: 283*61c4878aSAndroid Build Coastguard Worker 284*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 285*61c4878aSAndroid Build Coastguard Worker 286*61c4878aSAndroid Build Coastguard Worker pw::Vector<T> my_vec = ...; 287*61c4878aSAndroid Build Coastguard Worker 288*61c4878aSAndroid Build Coastguard Worker // ``my_vec`` looks to be moved here, but the resulting ``rvalue`` is never 289*61c4878aSAndroid Build Coastguard Worker // consumed by ``PossiblyFrobulate``. 290*61c4878aSAndroid Build Coastguard Worker PossiblyFrobulate(false, std::move(my_vec)); 291*61c4878aSAndroid Build Coastguard Worker 292*61c4878aSAndroid Build Coastguard Worker ... // some other long-running work 293*61c4878aSAndroid Build Coastguard Worker 294*61c4878aSAndroid Build Coastguard Worker // ``my_vec`` is still alive here, possibly causing excess memory usage, 295*61c4878aSAndroid Build Coastguard Worker // deadlocks, or even undefined behavior! 296*61c4878aSAndroid Build Coastguard Worker 297*61c4878aSAndroid Build Coastguard WorkerWhen conditionally consuming an argument, prefer instead to either accept 298*61c4878aSAndroid Build Coastguard Workerthe argument by-value or ensure that it is consumed by all control paths: 299*61c4878aSAndroid Build Coastguard Worker 300*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes**: Conditionally consumes by-value ``vector``: 301*61c4878aSAndroid Build Coastguard Worker :class: checkmark 302*61c4878aSAndroid Build Coastguard Worker 303*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 304*61c4878aSAndroid Build Coastguard Worker 305*61c4878aSAndroid Build Coastguard Worker void PossiblyFrobulate(bool should_frob, pw::Vector<T> vector) { 306*61c4878aSAndroid Build Coastguard Worker if (should_frob) { 307*61c4878aSAndroid Build Coastguard Worker Frobulate(std::move(vector)); 308*61c4878aSAndroid Build Coastguard Worker } 309*61c4878aSAndroid Build Coastguard Worker } 310*61c4878aSAndroid Build Coastguard Worker 311*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes**: Consumes ``vector`` on all control paths: 312*61c4878aSAndroid Build Coastguard Worker :class: checkmark 313*61c4878aSAndroid Build Coastguard Worker 314*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 315*61c4878aSAndroid Build Coastguard Worker 316*61c4878aSAndroid Build Coastguard Worker void PossiblyFrobulate(bool should_frob, pw::Vector<T>&& vector) { 317*61c4878aSAndroid Build Coastguard Worker if (should_frob) { 318*61c4878aSAndroid Build Coastguard Worker Frobulate(std::move(vector)); 319*61c4878aSAndroid Build Coastguard Worker } else { 320*61c4878aSAndroid Build Coastguard Worker [[maybe_unused]] auto to_discard = std::move(vector); 321*61c4878aSAndroid Build Coastguard Worker } 322*61c4878aSAndroid Build Coastguard Worker } 323*61c4878aSAndroid Build Coastguard Worker 324*61c4878aSAndroid Build Coastguard WorkerControl statements 325*61c4878aSAndroid Build Coastguard Worker================== 326*61c4878aSAndroid Build Coastguard Worker 327*61c4878aSAndroid Build Coastguard WorkerLoops and conditionals 328*61c4878aSAndroid Build Coastguard Worker---------------------- 329*61c4878aSAndroid Build Coastguard WorkerAll loops and conditional statements must use braces, and be on their own line. 330*61c4878aSAndroid Build Coastguard Worker 331*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes**: Always use braces for line conditionals and loops: 332*61c4878aSAndroid Build Coastguard Worker :class: checkmark 333*61c4878aSAndroid Build Coastguard Worker 334*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 335*61c4878aSAndroid Build Coastguard Worker 336*61c4878aSAndroid Build Coastguard Worker while (SomeCondition()) { 337*61c4878aSAndroid Build Coastguard Worker x += 2; 338*61c4878aSAndroid Build Coastguard Worker } 339*61c4878aSAndroid Build Coastguard Worker if (OtherCondition()) { 340*61c4878aSAndroid Build Coastguard Worker DoTheThing(); 341*61c4878aSAndroid Build Coastguard Worker } 342*61c4878aSAndroid Build Coastguard Worker 343*61c4878aSAndroid Build Coastguard Worker 344*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No**: Missing braces 345*61c4878aSAndroid Build Coastguard Worker :class: error 346*61c4878aSAndroid Build Coastguard Worker 347*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 348*61c4878aSAndroid Build Coastguard Worker 349*61c4878aSAndroid Build Coastguard Worker while (SomeCondition()) 350*61c4878aSAndroid Build Coastguard Worker x += 2; 351*61c4878aSAndroid Build Coastguard Worker if (OtherCondition()) 352*61c4878aSAndroid Build Coastguard Worker DoTheThing(); 353*61c4878aSAndroid Build Coastguard Worker 354*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No**: Statement on same line as condition 355*61c4878aSAndroid Build Coastguard Worker :class: error 356*61c4878aSAndroid Build Coastguard Worker 357*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 358*61c4878aSAndroid Build Coastguard Worker 359*61c4878aSAndroid Build Coastguard Worker while (SomeCondition()) { x += 2; } 360*61c4878aSAndroid Build Coastguard Worker if (OtherCondition()) { DoTheThing(); } 361*61c4878aSAndroid Build Coastguard Worker 362*61c4878aSAndroid Build Coastguard Worker 363*61c4878aSAndroid Build Coastguard WorkerThe syntax ``while (true)`` is preferred over ``for (;;)`` for infinite loops. 364*61c4878aSAndroid Build Coastguard Worker 365*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes**: 366*61c4878aSAndroid Build Coastguard Worker :class: checkmark 367*61c4878aSAndroid Build Coastguard Worker 368*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 369*61c4878aSAndroid Build Coastguard Worker 370*61c4878aSAndroid Build Coastguard Worker while (true) { 371*61c4878aSAndroid Build Coastguard Worker DoSomethingForever(); 372*61c4878aSAndroid Build Coastguard Worker } 373*61c4878aSAndroid Build Coastguard Worker 374*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No**: 375*61c4878aSAndroid Build Coastguard Worker :class: error 376*61c4878aSAndroid Build Coastguard Worker 377*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 378*61c4878aSAndroid Build Coastguard Worker 379*61c4878aSAndroid Build Coastguard Worker for (;;) { 380*61c4878aSAndroid Build Coastguard Worker DoSomethingForever(); 381*61c4878aSAndroid Build Coastguard Worker } 382*61c4878aSAndroid Build Coastguard Worker 383*61c4878aSAndroid Build Coastguard Worker 384*61c4878aSAndroid Build Coastguard WorkerPrefer early exit with ``return`` and ``continue`` 385*61c4878aSAndroid Build Coastguard Worker-------------------------------------------------- 386*61c4878aSAndroid Build Coastguard WorkerPrefer to exit early from functions and loops to simplify code. This is the 387*61c4878aSAndroid Build Coastguard Workersame same conventions as `LLVM 388*61c4878aSAndroid Build Coastguard Worker<https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code>`_. 389*61c4878aSAndroid Build Coastguard WorkerWe find this approach is superior to the "one return per function" style for a 390*61c4878aSAndroid Build Coastguard Workermultitude of reasons: 391*61c4878aSAndroid Build Coastguard Worker 392*61c4878aSAndroid Build Coastguard Worker* **Visually**, the code is easier to follow, and takes less horizontal screen 393*61c4878aSAndroid Build Coastguard Worker space. 394*61c4878aSAndroid Build Coastguard Worker* It makes it clear what part of the code is the **"main business" versus "edge 395*61c4878aSAndroid Build Coastguard Worker case handling"**. 396*61c4878aSAndroid Build Coastguard Worker* For **functions**, parameter checking is in its own section at the top of the 397*61c4878aSAndroid Build Coastguard Worker function, rather than scattered around in the fuction body. 398*61c4878aSAndroid Build Coastguard Worker* For **loops**, element checking is in its own section at the top of the loop, 399*61c4878aSAndroid Build Coastguard Worker rather than scattered around in the loop body. 400*61c4878aSAndroid Build Coastguard Worker* Commit **deltas are simpler to follow** in code reviews; since adding a new 401*61c4878aSAndroid Build Coastguard Worker parameter check or loop element condition doesn't cause an indentation change 402*61c4878aSAndroid Build Coastguard Worker in the rest of the function. 403*61c4878aSAndroid Build Coastguard Worker 404*61c4878aSAndroid Build Coastguard WorkerThe guidance applies in two cases: 405*61c4878aSAndroid Build Coastguard Worker 406*61c4878aSAndroid Build Coastguard Worker* **Function early exit** - Early exits are for function parameter checking 407*61c4878aSAndroid Build Coastguard Worker and edge case checking at the top. The main functionality follows. 408*61c4878aSAndroid Build Coastguard Worker* **Loop early exit** - Early exits in loops are for skipping an iteration 409*61c4878aSAndroid Build Coastguard Worker due to some edge case with an item getting iterated over. Loops may also 410*61c4878aSAndroid Build Coastguard Worker contain function exits, which should be structured the same way (see example 411*61c4878aSAndroid Build Coastguard Worker below). 412*61c4878aSAndroid Build Coastguard Worker 413*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes**: Exit early from functions; keeping the main handling 414*61c4878aSAndroid Build Coastguard Worker at the bottom and de-dentend. 415*61c4878aSAndroid Build Coastguard Worker :class: checkmark 416*61c4878aSAndroid Build Coastguard Worker 417*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 418*61c4878aSAndroid Build Coastguard Worker 419*61c4878aSAndroid Build Coastguard Worker Status DoSomething(Parameter parameter) { 420*61c4878aSAndroid Build Coastguard Worker // Parameter validation first; detecting incoming use errors. 421*61c4878aSAndroid Build Coastguard Worker PW_CHECK_INT_EQ(parameter.property(), 3, "Programmer error: frobnitz"); 422*61c4878aSAndroid Build Coastguard Worker 423*61c4878aSAndroid Build Coastguard Worker // Error case: Not in correct state. 424*61c4878aSAndroid Build Coastguard Worker if (parameter.other() == MyEnum::kBrokenState) { 425*61c4878aSAndroid Build Coastguard Worker LOG_ERROR("Device in strange state: %s", parametr.state_str()); 426*61c4878aSAndroid Build Coastguard Worker return Status::InvalidPrecondition(); 427*61c4878aSAndroid Build Coastguard Worker } 428*61c4878aSAndroid Build Coastguard Worker 429*61c4878aSAndroid Build Coastguard Worker // Error case: Not in low power mode; shouldn't do anything. 430*61c4878aSAndroid Build Coastguard Worker if (parameter.power() != MyEnum::kLowPower) { 431*61c4878aSAndroid Build Coastguard Worker LOG_ERROR("Not in low power mode"); 432*61c4878aSAndroid Build Coastguard Worker return Status::InvalidPrecondition(); 433*61c4878aSAndroid Build Coastguard Worker } 434*61c4878aSAndroid Build Coastguard Worker 435*61c4878aSAndroid Build Coastguard Worker // Main business for the function here. 436*61c4878aSAndroid Build Coastguard Worker MainBody(); 437*61c4878aSAndroid Build Coastguard Worker MoreMainBodyStuff(); 438*61c4878aSAndroid Build Coastguard Worker } 439*61c4878aSAndroid Build Coastguard Worker 440*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No**: Main body of function is buried and right creeping. 441*61c4878aSAndroid Build Coastguard Worker Even though this is shorter than the version preferred by Pigweed due to 442*61c4878aSAndroid Build Coastguard Worker factoring the return statement, the logical structure is less obvious. A 443*61c4878aSAndroid Build Coastguard Worker function in Pigweed containing **nested conditionals indicates that 444*61c4878aSAndroid Build Coastguard Worker something complicated is happening with the flow**; otherwise it would have 445*61c4878aSAndroid Build Coastguard Worker the early bail structure; so pay close attention. 446*61c4878aSAndroid Build Coastguard Worker :class: error 447*61c4878aSAndroid Build Coastguard Worker 448*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 449*61c4878aSAndroid Build Coastguard Worker 450*61c4878aSAndroid Build Coastguard Worker Status DoSomething(Parameter parameter) { 451*61c4878aSAndroid Build Coastguard Worker // Parameter validation first; detecting incoming use errors. 452*61c4878aSAndroid Build Coastguard Worker PW_CHECK_INT_EQ(parameter.property(), 3, "Programmer error: frobnitz"); 453*61c4878aSAndroid Build Coastguard Worker 454*61c4878aSAndroid Build Coastguard Worker // Error case: Not in correct state. 455*61c4878aSAndroid Build Coastguard Worker if (parameter.other() != MyEnum::kBrokenState) { 456*61c4878aSAndroid Build Coastguard Worker // Error case: Not in low power mode; shouldn't do anything. 457*61c4878aSAndroid Build Coastguard Worker if (parameter.power() == MyEnum::kLowPower) { 458*61c4878aSAndroid Build Coastguard Worker // Main business for the function here. 459*61c4878aSAndroid Build Coastguard Worker MainBody(); 460*61c4878aSAndroid Build Coastguard Worker MoreMainBodyStuff(); 461*61c4878aSAndroid Build Coastguard Worker } else { 462*61c4878aSAndroid Build Coastguard Worker LOG_ERROR("Not in low power mode"); 463*61c4878aSAndroid Build Coastguard Worker } 464*61c4878aSAndroid Build Coastguard Worker } else { 465*61c4878aSAndroid Build Coastguard Worker LOG_ERROR("Device in strange state: %s", parametr.state_str()); 466*61c4878aSAndroid Build Coastguard Worker } 467*61c4878aSAndroid Build Coastguard Worker return Status::InvalidPrecondition(); 468*61c4878aSAndroid Build Coastguard Worker } 469*61c4878aSAndroid Build Coastguard Worker 470*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes**: Bail early from loops; keeping the main handling at 471*61c4878aSAndroid Build Coastguard Worker the bottom and de-dentend. 472*61c4878aSAndroid Build Coastguard Worker :class: checkmark 473*61c4878aSAndroid Build Coastguard Worker 474*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 475*61c4878aSAndroid Build Coastguard Worker 476*61c4878aSAndroid Build Coastguard Worker for (int i = 0; i < LoopSize(); ++i) { 477*61c4878aSAndroid Build Coastguard Worker // Early skip of item based on edge condition. 478*61c4878aSAndroid Build Coastguard Worker if (!CommonCase()) { 479*61c4878aSAndroid Build Coastguard Worker continue; 480*61c4878aSAndroid Build Coastguard Worker } 481*61c4878aSAndroid Build Coastguard Worker // Early exit of function based on error case. 482*61c4878aSAndroid Build Coastguard Worker int my_measurement = GetSomeMeasurement(); 483*61c4878aSAndroid Build Coastguard Worker if (my_measurement < 10) { 484*61c4878aSAndroid Build Coastguard Worker LOG_ERROR("Found something strange; bailing"); 485*61c4878aSAndroid Build Coastguard Worker return Status::Unknown(); 486*61c4878aSAndroid Build Coastguard Worker } 487*61c4878aSAndroid Build Coastguard Worker 488*61c4878aSAndroid Build Coastguard Worker // Main body of the loop. 489*61c4878aSAndroid Build Coastguard Worker ProcessItem(my_items[i], my_measurement); 490*61c4878aSAndroid Build Coastguard Worker ProcessItemMore(my_items[i], my_measurement, other_details); 491*61c4878aSAndroid Build Coastguard Worker ... 492*61c4878aSAndroid Build Coastguard Worker } 493*61c4878aSAndroid Build Coastguard Worker 494*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No**: Right-creeping code with the main body buried inside 495*61c4878aSAndroid Build Coastguard Worker some nested conditional. This makes it harder to understand what is the 496*61c4878aSAndroid Build Coastguard Worker main purpose of the loop versus what is edge case handling. 497*61c4878aSAndroid Build Coastguard Worker :class: error 498*61c4878aSAndroid Build Coastguard Worker 499*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 500*61c4878aSAndroid Build Coastguard Worker 501*61c4878aSAndroid Build Coastguard Worker for (int i = 0; i < LoopSize(); ++i) { 502*61c4878aSAndroid Build Coastguard Worker if (CommonCase()) { 503*61c4878aSAndroid Build Coastguard Worker int my_measurement = GetSomeMeasurement(); 504*61c4878aSAndroid Build Coastguard Worker if (my_measurement >= 10) { 505*61c4878aSAndroid Build Coastguard Worker // Main body of the loop. 506*61c4878aSAndroid Build Coastguard Worker ProcessItem(my_items[i], my_measurement); 507*61c4878aSAndroid Build Coastguard Worker ProcessItemMore(my_items[i], my_measurement, other_details); 508*61c4878aSAndroid Build Coastguard Worker ... 509*61c4878aSAndroid Build Coastguard Worker } else { 510*61c4878aSAndroid Build Coastguard Worker LOG_ERROR("Found something strange; bailing"); 511*61c4878aSAndroid Build Coastguard Worker return Status::Unknown(); 512*61c4878aSAndroid Build Coastguard Worker } 513*61c4878aSAndroid Build Coastguard Worker } 514*61c4878aSAndroid Build Coastguard Worker } 515*61c4878aSAndroid Build Coastguard Worker 516*61c4878aSAndroid Build Coastguard WorkerThere are cases where this structure doesn't work, and in those cases, it is 517*61c4878aSAndroid Build Coastguard Workerfine to structure the code differently. 518*61c4878aSAndroid Build Coastguard Worker 519*61c4878aSAndroid Build Coastguard WorkerNo ``else`` after ``return`` or ``continue`` 520*61c4878aSAndroid Build Coastguard Worker-------------------------------------------- 521*61c4878aSAndroid Build Coastguard WorkerDo not put unnecessary ``} else {`` blocks after blocks that terminate with a 522*61c4878aSAndroid Build Coastguard Workerreturn, since this causes unnecessary rightward indentation creep. This 523*61c4878aSAndroid Build Coastguard Workerguidance pairs with the preference for early exits to reduce code duplication 524*61c4878aSAndroid Build Coastguard Workerand standardize loop/function structure. 525*61c4878aSAndroid Build Coastguard Worker 526*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes**: No else after return or continue 527*61c4878aSAndroid Build Coastguard Worker :class: checkmark 528*61c4878aSAndroid Build Coastguard Worker 529*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 530*61c4878aSAndroid Build Coastguard Worker 531*61c4878aSAndroid Build Coastguard Worker // Note lack of else block due to return. 532*61c4878aSAndroid Build Coastguard Worker if (Failure()) { 533*61c4878aSAndroid Build Coastguard Worker DoTheThing(); 534*61c4878aSAndroid Build Coastguard Worker return Status::ResourceExausted(); 535*61c4878aSAndroid Build Coastguard Worker } 536*61c4878aSAndroid Build Coastguard Worker 537*61c4878aSAndroid Build Coastguard Worker // Note lack of else block due to continue. 538*61c4878aSAndroid Build Coastguard Worker while (MyCondition()) { 539*61c4878aSAndroid Build Coastguard Worker if (SomeEarlyBail()) { 540*61c4878aSAndroid Build Coastguard Worker continue; 541*61c4878aSAndroid Build Coastguard Worker } 542*61c4878aSAndroid Build Coastguard Worker // Main handling of item 543*61c4878aSAndroid Build Coastguard Worker ... 544*61c4878aSAndroid Build Coastguard Worker } 545*61c4878aSAndroid Build Coastguard Worker 546*61c4878aSAndroid Build Coastguard Worker DoOtherThing(); 547*61c4878aSAndroid Build Coastguard Worker return OkStatus(); 548*61c4878aSAndroid Build Coastguard Worker 549*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No**: Else after return needlessly creeps right 550*61c4878aSAndroid Build Coastguard Worker :class: error 551*61c4878aSAndroid Build Coastguard Worker 552*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 553*61c4878aSAndroid Build Coastguard Worker 554*61c4878aSAndroid Build Coastguard Worker if (Failure()) { 555*61c4878aSAndroid Build Coastguard Worker DoTheThing(); 556*61c4878aSAndroid Build Coastguard Worker return Status::ResourceExausted(); 557*61c4878aSAndroid Build Coastguard Worker } else { 558*61c4878aSAndroid Build Coastguard Worker while (MyCondition()) { 559*61c4878aSAndroid Build Coastguard Worker if (SomeEarlyBail()) { 560*61c4878aSAndroid Build Coastguard Worker continue; 561*61c4878aSAndroid Build Coastguard Worker } else { 562*61c4878aSAndroid Build Coastguard Worker // Main handling of item 563*61c4878aSAndroid Build Coastguard Worker ... 564*61c4878aSAndroid Build Coastguard Worker } 565*61c4878aSAndroid Build Coastguard Worker } 566*61c4878aSAndroid Build Coastguard Worker DoOtherThing(); 567*61c4878aSAndroid Build Coastguard Worker return OkStatus(); 568*61c4878aSAndroid Build Coastguard Worker } 569*61c4878aSAndroid Build Coastguard Worker 570*61c4878aSAndroid Build Coastguard WorkerError handling 571*61c4878aSAndroid Build Coastguard Worker============== 572*61c4878aSAndroid Build Coastguard WorkerHistorically, exceptions have been avoided in embedded C++ as well as in general 573*61c4878aSAndroid Build Coastguard WorkerC++ code written at Google. Instead, assertions and error codes are used to 574*61c4878aSAndroid Build Coastguard Workercommunicate errors with less overhead. 575*61c4878aSAndroid Build Coastguard Worker 576*61c4878aSAndroid Build Coastguard WorkerSignal and propagate non-fatal errors with ``pw::Status`` and ``pw::Result``, 577*61c4878aSAndroid Build Coastguard Workerand assert/check for fatal errors. 578*61c4878aSAndroid Build Coastguard Worker 579*61c4878aSAndroid Build Coastguard WorkerAdd log statements to help with error tracking. See 580*61c4878aSAndroid Build Coastguard Worker:ref:`guidance below <docs-pw-style-cpp-logging>` on how to craft high-value, 581*61c4878aSAndroid Build Coastguard Workerlow-noise logs. 582*61c4878aSAndroid Build Coastguard Worker 583*61c4878aSAndroid Build Coastguard Worker.. note: 584*61c4878aSAndroid Build Coastguard Worker 585*61c4878aSAndroid Build Coastguard WorkerLike Google's C++ style guide, Pigweed does not use exceptions. The case for 586*61c4878aSAndroid Build Coastguard Workeravoiding exceptions on embedded is primarily due to reducing code size. 587*61c4878aSAndroid Build Coastguard Worker 588*61c4878aSAndroid Build Coastguard WorkerRecoverable errors 589*61c4878aSAndroid Build Coastguard Worker------------------ 590*61c4878aSAndroid Build Coastguard WorkerUse the following to report non-fatal failures from subroutines: 591*61c4878aSAndroid Build Coastguard Worker 592*61c4878aSAndroid Build Coastguard Worker- :cpp:type:`pw::Status`: Zero-overhead type that wraps a 593*61c4878aSAndroid Build Coastguard Worker :ref:`status code <module-pw_status-quickref>`. 594*61c4878aSAndroid Build Coastguard Worker- :ref:`pw::Result <module-pw_result>`: Union of a status code and a value. 595*61c4878aSAndroid Build Coastguard Worker- :ref:`pw::StatusWithSize <module-pw_status-guide-status-with-size>`: A status 596*61c4878aSAndroid Build Coastguard Worker combined with a size. Especially useful for operations which may partially 597*61c4878aSAndroid Build Coastguard Worker succeed, such as a write that sent some bytes before failing. 598*61c4878aSAndroid Build Coastguard Worker 599*61c4878aSAndroid Build Coastguard WorkerFatal errors 600*61c4878aSAndroid Build Coastguard Worker------------ 601*61c4878aSAndroid Build Coastguard WorkerUse :c:macro:`PW_ASSERT` and the :c:macro:`PW_CHECK` family of macros to halt 602*61c4878aSAndroid Build Coastguard Workerexecution on a fatal error. 603*61c4878aSAndroid Build Coastguard Worker 604*61c4878aSAndroid Build Coastguard Worker- These are appropriate when the security of the device is compromised. 605*61c4878aSAndroid Build Coastguard Worker 606*61c4878aSAndroid Build Coastguard Worker - Example: memory corruption is detected. 607*61c4878aSAndroid Build Coastguard Worker 608*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes** 609*61c4878aSAndroid Build Coastguard Worker :class: checkmark 610*61c4878aSAndroid Build Coastguard Worker 611*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 612*61c4878aSAndroid Build Coastguard Worker 613*61c4878aSAndroid Build Coastguard Worker PW_CHECK_NOTNULL(item->next); 614*61c4878aSAndroid Build Coastguard Worker PW_CHECK_PTR_EQ(item, item->next->prev); 615*61c4878aSAndroid Build Coastguard Worker 616*61c4878aSAndroid Build Coastguard Worker- These may be appropriate for instances of unambiguous programmer error. 617*61c4878aSAndroid Build Coastguard Worker 618*61c4878aSAndroid Build Coastguard Worker - Example: a caller passed a null pointer to a routine that explicitly 619*61c4878aSAndroid Build Coastguard Worker requires non-null pointers. 620*61c4878aSAndroid Build Coastguard Worker 621*61c4878aSAndroid Build Coastguard Worker.. warning:: 622*61c4878aSAndroid Build Coastguard Worker 623*61c4878aSAndroid Build Coastguard Worker Be very careful about introducing new assertions into existing code, or in 624*61c4878aSAndroid Build Coastguard Worker code paths that are not exhaustively tested, or any other scenario that may 625*61c4878aSAndroid Build Coastguard Worker result in crashes in fielded devices. 626*61c4878aSAndroid Build Coastguard Worker 627*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No**: May cause a runtime crash. 628*61c4878aSAndroid Build Coastguard Worker :class: error 629*61c4878aSAndroid Build Coastguard Worker 630*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 631*61c4878aSAndroid Build Coastguard Worker 632*61c4878aSAndroid Build Coastguard Worker StatusWithSize sws = kvs.Get("some-key", &out); 633*61c4878aSAndroid Build Coastguard Worker PW_CHECK_OK(sws.status()); 634*61c4878aSAndroid Build Coastguard Worker 635*61c4878aSAndroid Build Coastguard Worker The key may be missing from the :ref:`KVS <module-pw_kvs>` for a number of 636*61c4878aSAndroid Build Coastguard Worker reasons. It is likely better to surface this error to a higher level that can 637*61c4878aSAndroid Build Coastguard Worker decide how to handle a missing value. 638*61c4878aSAndroid Build Coastguard Worker 639*61c4878aSAndroid Build Coastguard WorkerInclude guards 640*61c4878aSAndroid Build Coastguard Worker============== 641*61c4878aSAndroid Build Coastguard WorkerThe first non-comment line of every header file must be ``#pragma once``. Do 642*61c4878aSAndroid Build Coastguard Workernot use traditional macro include guards. The ``#pragma once`` should come 643*61c4878aSAndroid Build Coastguard Workerdirectly after the Pigweed copyright block, with no blank line, followed by a 644*61c4878aSAndroid Build Coastguard Workerblank, like this: 645*61c4878aSAndroid Build Coastguard Worker 646*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 647*61c4878aSAndroid Build Coastguard Worker 648*61c4878aSAndroid Build Coastguard Worker // Copyright 2021 The Pigweed Authors 649*61c4878aSAndroid Build Coastguard Worker // 650*61c4878aSAndroid Build Coastguard Worker // Licensed under the Apache License, Version 2.0 (the "License"); you may not 651*61c4878aSAndroid Build Coastguard Worker // use this file except in compliance with the License. You may obtain a copy of 652*61c4878aSAndroid Build Coastguard Worker // the License at 653*61c4878aSAndroid Build Coastguard Worker // 654*61c4878aSAndroid Build Coastguard Worker // https://www.apache.org/licenses/LICENSE-2.0 655*61c4878aSAndroid Build Coastguard Worker // 656*61c4878aSAndroid Build Coastguard Worker // Unless required by applicable law or agreed to in writing, software 657*61c4878aSAndroid Build Coastguard Worker // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 658*61c4878aSAndroid Build Coastguard Worker // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 659*61c4878aSAndroid Build Coastguard Worker // License for the specific language governing permissions and limitations under 660*61c4878aSAndroid Build Coastguard Worker // the License. 661*61c4878aSAndroid Build Coastguard Worker #pragma once 662*61c4878aSAndroid Build Coastguard Worker 663*61c4878aSAndroid Build Coastguard Worker // Header file-level comment goes here... 664*61c4878aSAndroid Build Coastguard Worker 665*61c4878aSAndroid Build Coastguard Worker.. _docs-pw-style-cpp-logging: 666*61c4878aSAndroid Build Coastguard Worker 667*61c4878aSAndroid Build Coastguard WorkerLogging 668*61c4878aSAndroid Build Coastguard Worker======= 669*61c4878aSAndroid Build Coastguard WorkerGood logging can be incredibly useful in detecting and debugging errors. Log 670*61c4878aSAndroid Build Coastguard Workerquality is determined by the amount of useful information relative to overall 671*61c4878aSAndroid Build Coastguard Workeramount of logs. 672*61c4878aSAndroid Build Coastguard Worker 673*61c4878aSAndroid Build Coastguard WorkerLog in the right spot 674*61c4878aSAndroid Build Coastguard Worker--------------------- 675*61c4878aSAndroid Build Coastguard WorkerLimiting logs to only the most relevant sections of code can guide developers to 676*61c4878aSAndroid Build Coastguard Workerareas that require debugging. 677*61c4878aSAndroid Build Coastguard Worker 678*61c4878aSAndroid Build Coastguard Worker- **Log errors as soon as they can be umabiguously determined to be errors.** An 679*61c4878aSAndroid Build Coastguard Worker unambiguous error is one that will be reported to the caller of the module or 680*61c4878aSAndroid Build Coastguard Worker component. Avoid logging errors that are handled internally by the module or 681*61c4878aSAndroid Build Coastguard Worker component. 682*61c4878aSAndroid Build Coastguard Worker 683*61c4878aSAndroid Build Coastguard Worker - Example: A task manager would not log a failure to schedule a specific 684*61c4878aSAndroid Build Coastguard Worker worker from a pool, but may log the failure to find *any* worker in the 685*61c4878aSAndroid Build Coastguard Worker pool. 686*61c4878aSAndroid Build Coastguard Worker 687*61c4878aSAndroid Build Coastguard Worker .. admonition:: **No**: May log errors even if the call eventually succeeds. 688*61c4878aSAndroid Build Coastguard Worker :class: error 689*61c4878aSAndroid Build Coastguard Worker 690*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 691*61c4878aSAndroid Build Coastguard Worker 692*61c4878aSAndroid Build Coastguard Worker Status TaskManager::AssignToWorker(Task& task) { 693*61c4878aSAndroid Build Coastguard Worker for (auto& worker : pool_) { 694*61c4878aSAndroid Build Coastguard Worker if (worker.AssignTask(task).ok()) { 695*61c4878aSAndroid Build Coastguard Worker return OkStatus(); 696*61c4878aSAndroid Build Coastguard Worker } 697*61c4878aSAndroid Build Coastguard Worker } 698*61c4878aSAndroid Build Coastguard Worker return Status::ResourceExhausted(); 699*61c4878aSAndroid Build Coastguard Worker } 700*61c4878aSAndroid Build Coastguard Worker 701*61c4878aSAndroid Build Coastguard Worker Status Worker::Assign(Task& task) { 702*61c4878aSAndroid Build Coastguard Worker if (busy_) { 703*61c4878aSAndroid Build Coastguard Worker PW_LOG_DEBUG("failed to assign task to worker %zu", id_); 704*61c4878aSAndroid Build Coastguard Worker return Status::FailedPrecondition(); 705*61c4878aSAndroid Build Coastguard Worker } 706*61c4878aSAndroid Build Coastguard Worker // ... 707*61c4878aSAndroid Build Coastguard Worker } 708*61c4878aSAndroid Build Coastguard Worker 709*61c4878aSAndroid Build Coastguard Worker .. admonition:: **Yes**: Only logs when an actual failure has occurred. 710*61c4878aSAndroid Build Coastguard Worker :class: checkmark 711*61c4878aSAndroid Build Coastguard Worker 712*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 713*61c4878aSAndroid Build Coastguard Worker 714*61c4878aSAndroid Build Coastguard Worker Status TaskManager::AssignToWorker(Task& task) { 715*61c4878aSAndroid Build Coastguard Worker for (auto& worker : pool_) { 716*61c4878aSAndroid Build Coastguard Worker if (worker.AssignTask(task).ok()) { 717*61c4878aSAndroid Build Coastguard Worker return OkStatus(); 718*61c4878aSAndroid Build Coastguard Worker } 719*61c4878aSAndroid Build Coastguard Worker } 720*61c4878aSAndroid Build Coastguard Worker PW_LOG_DEBUG("failed to find a worker to handle the task"); 721*61c4878aSAndroid Build Coastguard Worker return Status::ResourceExhausted(); 722*61c4878aSAndroid Build Coastguard Worker } 723*61c4878aSAndroid Build Coastguard Worker 724*61c4878aSAndroid Build Coastguard Worker Status Worker::Assign(Task& task) { 725*61c4878aSAndroid Build Coastguard Worker if (busy_) { 726*61c4878aSAndroid Build Coastguard Worker return Status::FailedPrecondition(); 727*61c4878aSAndroid Build Coastguard Worker } 728*61c4878aSAndroid Build Coastguard Worker // ... 729*61c4878aSAndroid Build Coastguard Worker } 730*61c4878aSAndroid Build Coastguard Worker 731*61c4878aSAndroid Build Coastguard Worker 732*61c4878aSAndroid Build Coastguard Worker- **Log failures of an overall workflow at the level that it was initiated** to 733*61c4878aSAndroid Build Coastguard Worker provide context in which an error occurred. 734*61c4878aSAndroid Build Coastguard Worker 735*61c4878aSAndroid Build Coastguard Worker - Example: A widget may log that it could not perform a user-scheduled task 736*61c4878aSAndroid Build Coastguard Worker because the task manager returned an error. 737*61c4878aSAndroid Build Coastguard Worker 738*61c4878aSAndroid Build Coastguard Worker- **Limit the use of informational logs of non-failure conditions.** These 739*61c4878aSAndroid Build Coastguard Worker "heartbeat" logs can quickly accrue and become noise. If needed, keep the 740*61c4878aSAndroid Build Coastguard Worker frequency of these logs low, e.g. not more than once per second. 741*61c4878aSAndroid Build Coastguard Worker :c:macro:`PW_LOG_EVERY_N` and :c:macro:`PW_LOG_EVERY_N_DURATION` can be used 742*61c4878aSAndroid Build Coastguard Worker to rate-limit such logs. 743*61c4878aSAndroid Build Coastguard Worker 744*61c4878aSAndroid Build Coastguard Worker .. admonition:: **No**: May spew a large number of logs. 745*61c4878aSAndroid Build Coastguard Worker :class: error 746*61c4878aSAndroid Build Coastguard Worker 747*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 748*61c4878aSAndroid Build Coastguard Worker 749*61c4878aSAndroid Build Coastguard Worker void OnChunk(const Chunk& chunk) { 750*61c4878aSAndroid Build Coastguard Worker ++count_; 751*61c4878aSAndroid Build Coastguard Worker total_ += chunk.size(); 752*61c4878aSAndroid Build Coastguard Worker PW_LOG_DEBUG("Processed %zu chunks totaling %zu bytes", count_, total_); 753*61c4878aSAndroid Build Coastguard Worker // ... 754*61c4878aSAndroid Build Coastguard Worker } 755*61c4878aSAndroid Build Coastguard Worker 756*61c4878aSAndroid Build Coastguard Worker .. admonition:: **Yes**: Only logs once every 10 seconds. 757*61c4878aSAndroid Build Coastguard Worker :class: checkmark 758*61c4878aSAndroid Build Coastguard Worker 759*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 760*61c4878aSAndroid Build Coastguard Worker 761*61c4878aSAndroid Build Coastguard Worker void OnChunk(const Packet& packet) { 762*61c4878aSAndroid Build Coastguard Worker static constexpr auto kLogInterval = 763*61c4878aSAndroid Build Coastguard Worker chrono::SystemClock::for_at_least(std::chrono::seconds(10)); 764*61c4878aSAndroid Build Coastguard Worker ++count_; 765*61c4878aSAndroid Build Coastguard Worker total_ += packet.size(); 766*61c4878aSAndroid Build Coastguard Worker PW_LOG_EVERY_N_DURATION(PW_LOG_LEVEL_DEBUG, 767*61c4878aSAndroid Build Coastguard Worker kLogInterval, 768*61c4878aSAndroid Build Coastguard Worker "Processed %zu chunks totaling %zu bytes", 769*61c4878aSAndroid Build Coastguard Worker count_, 770*61c4878aSAndroid Build Coastguard Worker total_); 771*61c4878aSAndroid Build Coastguard Worker } 772*61c4878aSAndroid Build Coastguard Worker 773*61c4878aSAndroid Build Coastguard WorkerLog at the correct level 774*61c4878aSAndroid Build Coastguard Worker------------------------ 775*61c4878aSAndroid Build Coastguard Worker:ref:`Log levels <module-pw_log-levels>` indicate the seriousness of a message 776*61c4878aSAndroid Build Coastguard Workerand provide a simple mechanism for conditional logging and for log filtering. 777*61c4878aSAndroid Build Coastguard Worker 778*61c4878aSAndroid Build Coastguard Worker- **Downstream projects should use less filtered log levels**, as 779*61c4878aSAndroid Build Coastguard Worker project-specific errors more likely indicate an actionable failure. 780*61c4878aSAndroid Build Coastguard Worker 781*61c4878aSAndroid Build Coastguard Worker - Use :c:macro:`PW_LOG_CRITICAL` for failures that compromise the entire 782*61c4878aSAndroid Build Coastguard Worker device and will imminently halt or crash the device. 783*61c4878aSAndroid Build Coastguard Worker - Use :c:macro:`PW_LOG_ERROR` for failures that are more serious or harder to 784*61c4878aSAndroid Build Coastguard Worker recover from. 785*61c4878aSAndroid Build Coastguard Worker - Use :c:macro:`PW_LOG_WARN` for failures that are less serious or easier to 786*61c4878aSAndroid Build Coastguard Worker recover from. 787*61c4878aSAndroid Build Coastguard Worker - Use :c:macro:`PW_LOG_INFO` for informational logs of non-failure conditions. 788*61c4878aSAndroid Build Coastguard Worker 789*61c4878aSAndroid Build Coastguard Worker- **Libraries and upstream code should allow configurable logging.** Downstream 790*61c4878aSAndroid Build Coastguard Worker projects may want to disable library and module logging to save on code size, 791*61c4878aSAndroid Build Coastguard Worker or enable it to aid in debugging. 792*61c4878aSAndroid Build Coastguard Worker 793*61c4878aSAndroid Build Coastguard Worker - Use :c:macro:`PW_LOG_DEBUG` to log specific errors that the caller is 794*61c4878aSAndroid Build Coastguard Worker expected to handle. 795*61c4878aSAndroid Build Coastguard Worker 796*61c4878aSAndroid Build Coastguard Worker .. admonition:: **Yes** 797*61c4878aSAndroid Build Coastguard Worker :class: checkmark 798*61c4878aSAndroid Build Coastguard Worker 799*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 800*61c4878aSAndroid Build Coastguard Worker 801*61c4878aSAndroid Build Coastguard Worker if (stream.IsClosed()) { 802*61c4878aSAndroid Build Coastguard Worker PW_LOG_DEBUG("Stream closed unexpectedly"); 803*61c4878aSAndroid Build Coastguard Worker return Status::OutOfRange(); 804*61c4878aSAndroid Build Coastguard Worker } 805*61c4878aSAndroid Build Coastguard Worker 806*61c4878aSAndroid Build Coastguard Worker - Use :c:macro:`PW_LOG_INFO` and :c:macro:`PW_LOG_WARN` to communicate error 807*61c4878aSAndroid Build Coastguard Worker conditions that may not have a caller that can handle them. 808*61c4878aSAndroid Build Coastguard Worker 809*61c4878aSAndroid Build Coastguard Worker .. admonition:: **Yes** 810*61c4878aSAndroid Build Coastguard Worker :class: checkmark 811*61c4878aSAndroid Build Coastguard Worker 812*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 813*61c4878aSAndroid Build Coastguard Worker 814*61c4878aSAndroid Build Coastguard Worker while(!task_queue_.empty()) { 815*61c4878aSAndroid Build Coastguard Worker Task task = std::move(task_queue_.back()); 816*61c4878aSAndroid Build Coastguard Worker task_queue_.pop_back(); 817*61c4878aSAndroid Build Coastguard Worker if (task.HasExpired()) { 818*61c4878aSAndroid Build Coastguard Worker PW_LOG_INFO("Task %zu expired before being scheduled", task.id()); 819*61c4878aSAndroid Build Coastguard Worker continue; 820*61c4878aSAndroid Build Coastguard Worker } 821*61c4878aSAndroid Build Coastguard Worker Schedule(std::move(task)); 822*61c4878aSAndroid Build Coastguard Worker // ... 823*61c4878aSAndroid Build Coastguard Worker } 824*61c4878aSAndroid Build Coastguard Worker 825*61c4878aSAndroid Build Coastguard Worker - Set a :c:macro:`PW_LOG_LEVEL`. If logging in a module with a 826*61c4878aSAndroid Build Coastguard Worker :ref:`module configuration <module-structure-compile-time-configuration>`, 827*61c4878aSAndroid Build Coastguard Worker include a logging option and set :c:macro:`PW_LOG_LEVEL` to it. 828*61c4878aSAndroid Build Coastguard Worker 829*61c4878aSAndroid Build Coastguard Worker .. admonition:: **Yes** 830*61c4878aSAndroid Build Coastguard Worker :class: checkmark 831*61c4878aSAndroid Build Coastguard Worker 832*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 833*61c4878aSAndroid Build Coastguard Worker 834*61c4878aSAndroid Build Coastguard Worker // In my_module's config.h. Can be overridden at compile time. 835*61c4878aSAndroid Build Coastguard Worker #ifndef MY_MODULE_LOG_LEVEL 836*61c4878aSAndroid Build Coastguard Worker #define MY_MODULE_LOG_LEVEL PW_LOG_LEVEL_WARN 837*61c4878aSAndroid Build Coastguard Worker #endif MY_MODULE_LOG_LEVEL 838*61c4878aSAndroid Build Coastguard Worker 839*61c4878aSAndroid Build Coastguard Worker // In my_module's source files. 840*61c4878aSAndroid Build Coastguard Worker #include "my_module/config.h" 841*61c4878aSAndroid Build Coastguard Worker #define PW_LOG_LEVEL MY_MODULE_LOG_LEVEL 842*61c4878aSAndroid Build Coastguard Worker 843*61c4878aSAndroid Build Coastguard WorkerLog the right information 844*61c4878aSAndroid Build Coastguard Worker------------------------- 845*61c4878aSAndroid Build Coastguard WorkerLogging the most useful information requires considering what may be relevant to 846*61c4878aSAndroid Build Coastguard Workeran error and cannot be obtained another way. 847*61c4878aSAndroid Build Coastguard Worker 848*61c4878aSAndroid Build Coastguard Worker- **Include relevant context**, such as function parameters. 849*61c4878aSAndroid Build Coastguard Worker- **Capitalize your log message, but do not end with puncuation.** Log backends 850*61c4878aSAndroid Build Coastguard Worker typically combine your log message with additional information and format 851*61c4878aSAndroid Build Coastguard Worker them. 852*61c4878aSAndroid Build Coastguard Worker 853*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No** 854*61c4878aSAndroid Build Coastguard Worker :class: error 855*61c4878aSAndroid Build Coastguard Worker 856*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 857*61c4878aSAndroid Build Coastguard Worker 858*61c4878aSAndroid Build Coastguard Worker PW_LOG_DEBUG("the operation did not complete normally."); 859*61c4878aSAndroid Build Coastguard Worker 860*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes** 861*61c4878aSAndroid Build Coastguard Worker :class: checkmark 862*61c4878aSAndroid Build Coastguard Worker 863*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 864*61c4878aSAndroid Build Coastguard Worker 865*61c4878aSAndroid Build Coastguard Worker PW_LOG_DEBUG("The operation completed normally"); 866*61c4878aSAndroid Build Coastguard Worker 867*61c4878aSAndroid Build Coastguard Worker- **Set** :c:macro:`PW_LOG_MODULE_NAME` to include a 868*61c4878aSAndroid Build Coastguard Worker module name that you can filter on. 869*61c4878aSAndroid Build Coastguard Worker 870*61c4878aSAndroid Build Coastguard Worker.. admonition:: **Yes** 871*61c4878aSAndroid Build Coastguard Worker :class: checkmark 872*61c4878aSAndroid Build Coastguard Worker 873*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 874*61c4878aSAndroid Build Coastguard Worker 875*61c4878aSAndroid Build Coastguard Worker #define PW_LOG_MODULE_NAME "my_module" 876*61c4878aSAndroid Build Coastguard Worker 877*61c4878aSAndroid Build Coastguard Worker- **Do not include source location details.** The log backend can be configured 878*61c4878aSAndroid Build Coastguard Worker to add various :ref:`module-pw_log-logging_attributes` automatically. 879*61c4878aSAndroid Build Coastguard Worker 880*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No** 881*61c4878aSAndroid Build Coastguard Worker :class: error 882*61c4878aSAndroid Build Coastguard Worker 883*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 884*61c4878aSAndroid Build Coastguard Worker 885*61c4878aSAndroid Build Coastguard Worker PW_LOG_DEBUG("%s:%d: %s called", __FILE__, __LINE__, __PRETTY_FUNCTION__); 886*61c4878aSAndroid Build Coastguard Worker 887*61c4878aSAndroid Build Coastguard Worker- **Do not log** :cpp:type:`pw::Status` **details.** If you are logging and 888*61c4878aSAndroid Build Coastguard Worker returning an error as a result of a subroutine that returned an error, it is 889*61c4878aSAndroid Build Coastguard Worker likely that a log statement can be added closer to where that error was 890*61c4878aSAndroid Build Coastguard Worker detected. 891*61c4878aSAndroid Build Coastguard Worker 892*61c4878aSAndroid Build Coastguard Worker.. admonition:: **No** 893*61c4878aSAndroid Build Coastguard Worker :class: error 894*61c4878aSAndroid Build Coastguard Worker 895*61c4878aSAndroid Build Coastguard Worker .. code-block:: cpp 896*61c4878aSAndroid Build Coastguard Worker 897*61c4878aSAndroid Build Coastguard Worker Result<Message> ReadAndDecode(Stream& stream) { 898*61c4878aSAndroid Build Coastguard Worker Result<EncodedMessage> result = ReadEncodedMessage(stream); 899*61c4878aSAndroid Build Coastguard Worker if (!result.ok()) { 900*61c4878aSAndroid Build Coastguard Worker Status status = result.status(); 901*61c4878aSAndroid Build Coastguard Worker PW_LOG_DEBUG("Failed to read message: %s", 902*61c4878aSAndroid Build Coastguard Worker pw_StatusString(status.code)); 903*61c4878aSAndroid Build Coastguard Worker return status; 904*61c4878aSAndroid Build Coastguard Worker } 905*61c4878aSAndroid Build Coastguard Worker // ... 906*61c4878aSAndroid Build Coastguard Worker } 907*61c4878aSAndroid Build Coastguard Worker 908*61c4878aSAndroid Build Coastguard WorkerMemory allocation 909*61c4878aSAndroid Build Coastguard Worker================= 910*61c4878aSAndroid Build Coastguard WorkerDynamic memory allocation can be problematic. Heap allocations and deallocations 911*61c4878aSAndroid Build Coastguard Workeroccupy valuable CPU cycles. Memory usage becomes nondeterministic, which can 912*61c4878aSAndroid Build Coastguard Workerresult in a system crashing without a clear culprit. 913*61c4878aSAndroid Build Coastguard Worker 914*61c4878aSAndroid Build Coastguard WorkerTo keep Pigweed portable, core Pigweed code is not permitted to dynamically 915*61c4878aSAndroid Build Coastguard Worker(heap) allocate memory, such as with ``malloc`` or ``new``. All memory should be 916*61c4878aSAndroid Build Coastguard Workerallocated with automatic (stack) or static (global) storage duration. Pigweed 917*61c4878aSAndroid Build Coastguard Workermust not use C++ libraries that use dynamic allocation. 918*61c4878aSAndroid Build Coastguard Worker 919*61c4878aSAndroid Build Coastguard WorkerProjects that use Pigweed are free to use dynamic allocation, provided they 920*61c4878aSAndroid Build Coastguard Workerhave selected a target that enables the heap. 921*61c4878aSAndroid Build Coastguard Worker 922*61c4878aSAndroid Build Coastguard WorkerNaming 923*61c4878aSAndroid Build Coastguard Worker====== 924*61c4878aSAndroid Build Coastguard WorkerEntities shall be named according to the `Google style guide 925*61c4878aSAndroid Build Coastguard Worker<https://google.github.io/styleguide/cppguide.html>`_, with the following 926*61c4878aSAndroid Build Coastguard Workeradditional requirements. 927*61c4878aSAndroid Build Coastguard Worker 928*61c4878aSAndroid Build Coastguard WorkerC++ code 929*61c4878aSAndroid Build Coastguard Worker-------- 930*61c4878aSAndroid Build Coastguard Worker* All Pigweed C++ code must be in the ``pw`` namespace. Namespaces for modules 931*61c4878aSAndroid Build Coastguard Worker should be nested under ``pw``. For example, ``pw::string::Format()``. 932*61c4878aSAndroid Build Coastguard Worker* Whenever possible, private code should be in a source (.cc) file and placed in 933*61c4878aSAndroid Build Coastguard Worker anonymous namespace nested under ``pw``. Unit tests must be declared in an 934*61c4878aSAndroid Build Coastguard Worker anonymous namespace to avoid potential linking issues when building multiple 935*61c4878aSAndroid Build Coastguard Worker tests in one binary. 936*61c4878aSAndroid Build Coastguard Worker* If private code must be exposed in a header file, it must be in a namespace 937*61c4878aSAndroid Build Coastguard Worker nested under ``pw``. The namespace may be named for its subsystem or use a 938*61c4878aSAndroid Build Coastguard Worker name that designates it as private, such as ``internal``. 939*61c4878aSAndroid Build Coastguard Worker* Template arguments for non-type names (e.g. ``template <int kFooBar>``) should 940*61c4878aSAndroid Build Coastguard Worker follow the constexpr and const variable Google naming convention, which means 941*61c4878aSAndroid Build Coastguard Worker k prefixed camel case (e.g. ``kCamelCase``). This matches the Google C++ 942*61c4878aSAndroid Build Coastguard Worker style for variable naming, however the wording in the official style guide 943*61c4878aSAndroid Build Coastguard Worker isn't explicit for template arguments and could be interpreted to use 944*61c4878aSAndroid Build Coastguard Worker ``foo_bar`` style naming. For consistency with other variables whose value is 945*61c4878aSAndroid Build Coastguard Worker always fixed for the duration of the program, the naming convention is 946*61c4878aSAndroid Build Coastguard Worker ``kCamelCase``, and so that is the style we use in Pigweed. 947*61c4878aSAndroid Build Coastguard Worker* Trivial membor accessors should be named with ``snake_case()``. The Google 948*61c4878aSAndroid Build Coastguard Worker C++ style allows either ``snake_case()`` or ``CapsCase()``, but Pigweed 949*61c4878aSAndroid Build Coastguard Worker always uses ``snake_case()``. 950*61c4878aSAndroid Build Coastguard Worker* Abstract base classes should be named generically, with derived types named 951*61c4878aSAndroid Build Coastguard Worker specifically. For example, ``Stream`` is an abstract base, and 952*61c4878aSAndroid Build Coastguard Worker ``SocketStream`` and ``StdioStream`` are an implementations of that 953*61c4878aSAndroid Build Coastguard Worker interface. Any prefix or postfix indicating whether something is abstract or 954*61c4878aSAndroid Build Coastguard Worker concrete is not permitted; for example, ``IStream`` or ``SocketStreamImpl`` 955*61c4878aSAndroid Build Coastguard Worker are both not permitted. These pre-/post-fixes add additional visual noise and 956*61c4878aSAndroid Build Coastguard Worker are irrelevant to consumers of these interfaces. 957*61c4878aSAndroid Build Coastguard Worker 958*61c4878aSAndroid Build Coastguard WorkerC code 959*61c4878aSAndroid Build Coastguard Worker------ 960*61c4878aSAndroid Build Coastguard WorkerIn general, C symbols should be prefixed with the module name. If the symbol is 961*61c4878aSAndroid Build Coastguard Workernot associated with a module, use just ``pw`` as the module name. Facade 962*61c4878aSAndroid Build Coastguard Workerbackends may chose to prefix symbols with the facade's name to help reduce the 963*61c4878aSAndroid Build Coastguard Workerlength of the prefix. 964*61c4878aSAndroid Build Coastguard Worker 965*61c4878aSAndroid Build Coastguard Worker* Public names used by C code must be prefixed with the module name (e.g. 966*61c4878aSAndroid Build Coastguard Worker ``pw_tokenizer_*``). 967*61c4878aSAndroid Build Coastguard Worker* If private code must be exposed in a header, private names used by C code must 968*61c4878aSAndroid Build Coastguard Worker be prefixed with an underscore followed by the module name (e.g. 969*61c4878aSAndroid Build Coastguard Worker ``_pw_assert_*``). 970*61c4878aSAndroid Build Coastguard Worker* Avoid writing C source (.c) files in Pigweed. Prefer to write C++ code with C 971*61c4878aSAndroid Build Coastguard Worker linkage using ``extern "C"``. Within C source, private C functions and 972*61c4878aSAndroid Build Coastguard Worker variables must be named with the ``_pw_my_module_*`` prefix and should be 973*61c4878aSAndroid Build Coastguard Worker declared ``static`` whenever possible; for example, 974*61c4878aSAndroid Build Coastguard Worker ``_pw_my_module_MyPrivateFunction``. 975*61c4878aSAndroid Build Coastguard Worker* The C prefix rules apply to 976*61c4878aSAndroid Build Coastguard Worker 977*61c4878aSAndroid Build Coastguard Worker * C functions (``int pw_foo_FunctionName(void);``), 978*61c4878aSAndroid Build Coastguard Worker * variables used by C code (``int pw_foo_variable_name;``), 979*61c4878aSAndroid Build Coastguard Worker * constant variables used by C code (``const int pw_foo_kConstantName;``), 980*61c4878aSAndroid Build Coastguard Worker * structs used by C code (``typedef struct {} pw_foo_StructName;``), and 981*61c4878aSAndroid Build Coastguard Worker * all of the above for ``extern "C"`` names in C++ code. 982*61c4878aSAndroid Build Coastguard Worker 983*61c4878aSAndroid Build Coastguard Worker The prefix does not apply to struct members, which use normal Google style. 984*61c4878aSAndroid Build Coastguard Worker 985*61c4878aSAndroid Build Coastguard WorkerPreprocessor macros 986*61c4878aSAndroid Build Coastguard Worker------------------- 987*61c4878aSAndroid Build Coastguard Worker* Public Pigweed macros must be prefixed with the module name (e.g. 988*61c4878aSAndroid Build Coastguard Worker ``PW_MY_MODULE_*``). 989*61c4878aSAndroid Build Coastguard Worker* Private Pigweed macros must be prefixed with an underscore followed by the 990*61c4878aSAndroid Build Coastguard Worker module name (e.g. ``_PW_MY_MODULE_*``). (This style may change, see 991*61c4878aSAndroid Build Coastguard Worker `b/234886184 <https://issuetracker.google.com/issues/234886184>`_). 992*61c4878aSAndroid Build Coastguard Worker 993*61c4878aSAndroid Build Coastguard Worker**Example** 994*61c4878aSAndroid Build Coastguard Worker 995*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 996*61c4878aSAndroid Build Coastguard Worker 997*61c4878aSAndroid Build Coastguard Worker namespace pw::my_module { 998*61c4878aSAndroid Build Coastguard Worker namespace nested_namespace { 999*61c4878aSAndroid Build Coastguard Worker 1000*61c4878aSAndroid Build Coastguard Worker // C++ names (types, variables, functions) must be in the pw namespace. 1001*61c4878aSAndroid Build Coastguard Worker // They are named according to the Google style guide. 1002*61c4878aSAndroid Build Coastguard Worker constexpr int kGlobalConstant = 123; 1003*61c4878aSAndroid Build Coastguard Worker 1004*61c4878aSAndroid Build Coastguard Worker // Prefer using functions over extern global variables. 1005*61c4878aSAndroid Build Coastguard Worker extern int global_variable; 1006*61c4878aSAndroid Build Coastguard Worker 1007*61c4878aSAndroid Build Coastguard Worker class Class {}; 1008*61c4878aSAndroid Build Coastguard Worker 1009*61c4878aSAndroid Build Coastguard Worker void Function(); 1010*61c4878aSAndroid Build Coastguard Worker 1011*61c4878aSAndroid Build Coastguard Worker extern "C" { 1012*61c4878aSAndroid Build Coastguard Worker 1013*61c4878aSAndroid Build Coastguard Worker // Public Pigweed code used from C must be prefixed with pw_. 1014*61c4878aSAndroid Build Coastguard Worker extern const int pw_my_module_kGlobalConstant; 1015*61c4878aSAndroid Build Coastguard Worker 1016*61c4878aSAndroid Build Coastguard Worker extern int pw_my_module_global_variable; 1017*61c4878aSAndroid Build Coastguard Worker 1018*61c4878aSAndroid Build Coastguard Worker void pw_my_module_Function(void); 1019*61c4878aSAndroid Build Coastguard Worker 1020*61c4878aSAndroid Build Coastguard Worker typedef struct { 1021*61c4878aSAndroid Build Coastguard Worker int member_variable; 1022*61c4878aSAndroid Build Coastguard Worker } pw_my_module_Struct; 1023*61c4878aSAndroid Build Coastguard Worker 1024*61c4878aSAndroid Build Coastguard Worker // Private Pigweed code used from C must be prefixed with _pw_. 1025*61c4878aSAndroid Build Coastguard Worker extern const int _pw_my_module_kPrivateGlobalConstant; 1026*61c4878aSAndroid Build Coastguard Worker 1027*61c4878aSAndroid Build Coastguard Worker extern int _pw_my_module_private_global_variable; 1028*61c4878aSAndroid Build Coastguard Worker 1029*61c4878aSAndroid Build Coastguard Worker void _pw_my_module_PrivateFunction(void); 1030*61c4878aSAndroid Build Coastguard Worker 1031*61c4878aSAndroid Build Coastguard Worker typedef struct { 1032*61c4878aSAndroid Build Coastguard Worker int member_variable; 1033*61c4878aSAndroid Build Coastguard Worker } _pw_my_module_PrivateStruct; 1034*61c4878aSAndroid Build Coastguard Worker 1035*61c4878aSAndroid Build Coastguard Worker } // extern "C" 1036*61c4878aSAndroid Build Coastguard Worker 1037*61c4878aSAndroid Build Coastguard Worker // Public macros must be prefixed with PW_. 1038*61c4878aSAndroid Build Coastguard Worker #define PW_MY_MODULE_PUBLIC_MACRO(arg) arg 1039*61c4878aSAndroid Build Coastguard Worker 1040*61c4878aSAndroid Build Coastguard Worker // Private macros must be prefixed with _PW_. 1041*61c4878aSAndroid Build Coastguard Worker #define _PW_MY_MODULE_PRIVATE_MACRO(arg) arg 1042*61c4878aSAndroid Build Coastguard Worker 1043*61c4878aSAndroid Build Coastguard Worker } // namespace nested_namespace 1044*61c4878aSAndroid Build Coastguard Worker } // namespace pw::my_module 1045*61c4878aSAndroid Build Coastguard Worker 1046*61c4878aSAndroid Build Coastguard WorkerSee :ref:`docs-pw-style-macros` for details about macro usage. 1047*61c4878aSAndroid Build Coastguard Worker 1048*61c4878aSAndroid Build Coastguard WorkerNamespace scope formatting 1049*61c4878aSAndroid Build Coastguard Worker========================== 1050*61c4878aSAndroid Build Coastguard WorkerAll non-indented blocks (namespaces, ``extern "C"`` blocks, and preprocessor 1051*61c4878aSAndroid Build Coastguard Workerconditionals) must have a comment on their closing line with the 1052*61c4878aSAndroid Build Coastguard Workercontents of the starting line. 1053*61c4878aSAndroid Build Coastguard Worker 1054*61c4878aSAndroid Build Coastguard WorkerAll nested namespaces should be declared together with no blank lines between 1055*61c4878aSAndroid Build Coastguard Workerthem. 1056*61c4878aSAndroid Build Coastguard Worker 1057*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1058*61c4878aSAndroid Build Coastguard Worker 1059*61c4878aSAndroid Build Coastguard Worker #include "some/header.h" 1060*61c4878aSAndroid Build Coastguard Worker 1061*61c4878aSAndroid Build Coastguard Worker namespace pw::nested { 1062*61c4878aSAndroid Build Coastguard Worker namespace { 1063*61c4878aSAndroid Build Coastguard Worker 1064*61c4878aSAndroid Build Coastguard Worker constexpr int kAnonConstantGoesHere = 0; 1065*61c4878aSAndroid Build Coastguard Worker 1066*61c4878aSAndroid Build Coastguard Worker } // namespace 1067*61c4878aSAndroid Build Coastguard Worker 1068*61c4878aSAndroid Build Coastguard Worker namespace other { 1069*61c4878aSAndroid Build Coastguard Worker 1070*61c4878aSAndroid Build Coastguard Worker const char* SomeClass::yes = "no"; 1071*61c4878aSAndroid Build Coastguard Worker 1072*61c4878aSAndroid Build Coastguard Worker bool ThisIsAFunction() { 1073*61c4878aSAndroid Build Coastguard Worker #if PW_CONFIG_IS_SET 1074*61c4878aSAndroid Build Coastguard Worker return true; 1075*61c4878aSAndroid Build Coastguard Worker #else 1076*61c4878aSAndroid Build Coastguard Worker return false; 1077*61c4878aSAndroid Build Coastguard Worker #endif // PW_CONFIG_IS_SET 1078*61c4878aSAndroid Build Coastguard Worker } 1079*61c4878aSAndroid Build Coastguard Worker 1080*61c4878aSAndroid Build Coastguard Worker extern "C" { 1081*61c4878aSAndroid Build Coastguard Worker 1082*61c4878aSAndroid Build Coastguard Worker const int pw_kSomeConstant = 10; 1083*61c4878aSAndroid Build Coastguard Worker int pw_some_global_variable = 600; 1084*61c4878aSAndroid Build Coastguard Worker 1085*61c4878aSAndroid Build Coastguard Worker void pw_CFunction() { ... } 1086*61c4878aSAndroid Build Coastguard Worker 1087*61c4878aSAndroid Build Coastguard Worker } // extern "C" 1088*61c4878aSAndroid Build Coastguard Worker 1089*61c4878aSAndroid Build Coastguard Worker } // namespace 1090*61c4878aSAndroid Build Coastguard Worker } // namespace pw::nested 1091*61c4878aSAndroid Build Coastguard Worker 1092*61c4878aSAndroid Build Coastguard WorkerUsing directives for literals 1093*61c4878aSAndroid Build Coastguard Worker============================= 1094*61c4878aSAndroid Build Coastguard Worker`Using-directives 1095*61c4878aSAndroid Build Coastguard Worker<https://en.cppreference.com/w/cpp/language/namespace#Using-directives>`_ (e.g. 1096*61c4878aSAndroid Build Coastguard Worker``using namespace ...``) are permitted in implementation files only for the 1097*61c4878aSAndroid Build Coastguard Workerpurposes of importing literals such as ``std::chrono_literals`` or 1098*61c4878aSAndroid Build Coastguard Worker``pw::bytes::unit_literals``. Namespaces that contain any symbols other than 1099*61c4878aSAndroid Build Coastguard Workerliterals are not permitted in a using-directive. This guidance also has no 1100*61c4878aSAndroid Build Coastguard Workerimpact on `using-declarations 1101*61c4878aSAndroid Build Coastguard Worker<https://en.cppreference.com/w/cpp/language/namespace#Using-declarations>`_ 1102*61c4878aSAndroid Build Coastguard Worker(e.g. ``using foo::Bar;``). 1103*61c4878aSAndroid Build Coastguard Worker 1104*61c4878aSAndroid Build Coastguard WorkerRationale: Literals improve code readability, making units clearer at the point 1105*61c4878aSAndroid Build Coastguard Workerof definition. 1106*61c4878aSAndroid Build Coastguard Worker 1107*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1108*61c4878aSAndroid Build Coastguard Worker 1109*61c4878aSAndroid Build Coastguard Worker using namespace std::chrono; // Not allowed 1110*61c4878aSAndroid Build Coastguard Worker using namespace std::literals::chrono_literals; // Allowed 1111*61c4878aSAndroid Build Coastguard Worker 1112*61c4878aSAndroid Build Coastguard Worker constexpr std::chrono::duration delay = 250ms; 1113*61c4878aSAndroid Build Coastguard Worker 1114*61c4878aSAndroid Build Coastguard WorkerPointers and references 1115*61c4878aSAndroid Build Coastguard Worker======================= 1116*61c4878aSAndroid Build Coastguard WorkerFor pointer and reference types, place the asterisk or ampersand next to the 1117*61c4878aSAndroid Build Coastguard Workertype. 1118*61c4878aSAndroid Build Coastguard Worker 1119*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1120*61c4878aSAndroid Build Coastguard Worker 1121*61c4878aSAndroid Build Coastguard Worker int* const number = &that_thing; 1122*61c4878aSAndroid Build Coastguard Worker constexpr const char* kString = "theory!" 1123*61c4878aSAndroid Build Coastguard Worker 1124*61c4878aSAndroid Build Coastguard Worker bool FindTheOneRing(const Region& where_to_look) { ... } 1125*61c4878aSAndroid Build Coastguard Worker 1126*61c4878aSAndroid Build Coastguard WorkerPrefer storing references over storing pointers. Pointers are required when the 1127*61c4878aSAndroid Build Coastguard Workerpointer can change its target or may be ``nullptr``. Otherwise, a reference or 1128*61c4878aSAndroid Build Coastguard Workerconst reference should be used. 1129*61c4878aSAndroid Build Coastguard Worker 1130*61c4878aSAndroid Build Coastguard Worker.. _docs-pw-style-macros: 1131*61c4878aSAndroid Build Coastguard Worker 1132*61c4878aSAndroid Build Coastguard WorkerPreprocessor macros 1133*61c4878aSAndroid Build Coastguard Worker=================== 1134*61c4878aSAndroid Build Coastguard WorkerMacros should only be used when they significantly improve upon the C++ code 1135*61c4878aSAndroid Build Coastguard Workerthey replace. Macros should make code more readable, robust, and safe, or 1136*61c4878aSAndroid Build Coastguard Workerprovide features not possible with standard C++, such as stringification, line 1137*61c4878aSAndroid Build Coastguard Workernumber capturing, or conditional compilation. When possible, use C++ constructs 1138*61c4878aSAndroid Build Coastguard Workerlike constexpr variables in place of macros. Never use macros as constants, 1139*61c4878aSAndroid Build Coastguard Workerexcept when a string literal is needed or the value must be used by C code. 1140*61c4878aSAndroid Build Coastguard Worker 1141*61c4878aSAndroid Build Coastguard WorkerWhen macros are needed, the macros should be accompanied with extensive tests 1142*61c4878aSAndroid Build Coastguard Workerto ensure the macros are hard to use wrong. 1143*61c4878aSAndroid Build Coastguard Worker 1144*61c4878aSAndroid Build Coastguard WorkerStand-alone statement macros 1145*61c4878aSAndroid Build Coastguard Worker---------------------------- 1146*61c4878aSAndroid Build Coastguard WorkerMacros that are standalone statements must require the caller to terminate the 1147*61c4878aSAndroid Build Coastguard Workermacro invocation with a semicolon (see `Swalling the Semicolon 1148*61c4878aSAndroid Build Coastguard Worker<https://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html>`_). For 1149*61c4878aSAndroid Build Coastguard Workerexample, the following does *not* conform to Pigweed's macro style: 1150*61c4878aSAndroid Build Coastguard Worker 1151*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1152*61c4878aSAndroid Build Coastguard Worker 1153*61c4878aSAndroid Build Coastguard Worker // BAD! Definition has built-in semicolon. 1154*61c4878aSAndroid Build Coastguard Worker #define PW_LOG_IF_BAD(mj) \ 1155*61c4878aSAndroid Build Coastguard Worker CallSomeFunction(mj); 1156*61c4878aSAndroid Build Coastguard Worker 1157*61c4878aSAndroid Build Coastguard Worker // BAD! Compiles without error; semicolon is missing. 1158*61c4878aSAndroid Build Coastguard Worker PW_LOG_IF_BAD("foo") 1159*61c4878aSAndroid Build Coastguard Worker 1160*61c4878aSAndroid Build Coastguard WorkerHere's how to do this instead: 1161*61c4878aSAndroid Build Coastguard Worker 1162*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1163*61c4878aSAndroid Build Coastguard Worker 1164*61c4878aSAndroid Build Coastguard Worker // GOOD; requires semicolon to compile. 1165*61c4878aSAndroid Build Coastguard Worker #define PW_LOG_IF_BAD(mj) \ 1166*61c4878aSAndroid Build Coastguard Worker CallSomeFunction(mj) 1167*61c4878aSAndroid Build Coastguard Worker 1168*61c4878aSAndroid Build Coastguard Worker // GOOD; fails to compile due to lacking semicolon. 1169*61c4878aSAndroid Build Coastguard Worker PW_LOG_IF_BAD("foo") 1170*61c4878aSAndroid Build Coastguard Worker 1171*61c4878aSAndroid Build Coastguard WorkerFor macros in function scope that do not already require a semicolon, the 1172*61c4878aSAndroid Build Coastguard Workercontents can be placed in a ``do { ... } while (0)`` loop. 1173*61c4878aSAndroid Build Coastguard Worker 1174*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1175*61c4878aSAndroid Build Coastguard Worker 1176*61c4878aSAndroid Build Coastguard Worker #define PW_LOG_IF_BAD(mj) \ 1177*61c4878aSAndroid Build Coastguard Worker do { \ 1178*61c4878aSAndroid Build Coastguard Worker if (mj.Bad()) { \ 1179*61c4878aSAndroid Build Coastguard Worker Log(#mj " is bad") \ 1180*61c4878aSAndroid Build Coastguard Worker } \ 1181*61c4878aSAndroid Build Coastguard Worker } while (0) 1182*61c4878aSAndroid Build Coastguard Worker 1183*61c4878aSAndroid Build Coastguard WorkerStandalone macros at global scope that do not already require a semicolon can 1184*61c4878aSAndroid Build Coastguard Workeradd a ``static_assert`` declaration statement as their last line. 1185*61c4878aSAndroid Build Coastguard Worker 1186*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1187*61c4878aSAndroid Build Coastguard Worker 1188*61c4878aSAndroid Build Coastguard Worker #define PW_NEAT_THING(thing) \ 1189*61c4878aSAndroid Build Coastguard Worker bool IsNeat_##thing() { return true; } \ 1190*61c4878aSAndroid Build Coastguard Worker static_assert(true, "Macros must be terminated with a semicolon") 1191*61c4878aSAndroid Build Coastguard Worker 1192*61c4878aSAndroid Build Coastguard WorkerPrivate macros in public headers 1193*61c4878aSAndroid Build Coastguard Worker-------------------------------- 1194*61c4878aSAndroid Build Coastguard WorkerPrivate macros in public headers must be prefixed with ``_PW_``, even if they 1195*61c4878aSAndroid Build Coastguard Workerare undefined after use; this prevents collisions with downstream users. For 1196*61c4878aSAndroid Build Coastguard Workerexample: 1197*61c4878aSAndroid Build Coastguard Worker 1198*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1199*61c4878aSAndroid Build Coastguard Worker 1200*61c4878aSAndroid Build Coastguard Worker #define _PW_MY_SPECIAL_MACRO(op) ... 1201*61c4878aSAndroid Build Coastguard Worker ... 1202*61c4878aSAndroid Build Coastguard Worker // Code that uses _PW_MY_SPECIAL_MACRO() 1203*61c4878aSAndroid Build Coastguard Worker ... 1204*61c4878aSAndroid Build Coastguard Worker #undef _PW_MY_SPECIAL_MACRO 1205*61c4878aSAndroid Build Coastguard Worker 1206*61c4878aSAndroid Build Coastguard WorkerMacros in private implementation files (.cc) 1207*61c4878aSAndroid Build Coastguard Worker-------------------------------------------- 1208*61c4878aSAndroid Build Coastguard WorkerMacros within .cc files that should only be used within one file should be 1209*61c4878aSAndroid Build Coastguard Workerundefined after their last use; for example: 1210*61c4878aSAndroid Build Coastguard Worker 1211*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1212*61c4878aSAndroid Build Coastguard Worker 1213*61c4878aSAndroid Build Coastguard Worker #define DEFINE_OPERATOR(op) \ 1214*61c4878aSAndroid Build Coastguard Worker T operator ## op(T x, T y) { return x op y; } \ 1215*61c4878aSAndroid Build Coastguard Worker static_assert(true, "Macros must be terminated with a semicolon") \ 1216*61c4878aSAndroid Build Coastguard Worker 1217*61c4878aSAndroid Build Coastguard Worker DEFINE_OPERATOR(+); 1218*61c4878aSAndroid Build Coastguard Worker DEFINE_OPERATOR(-); 1219*61c4878aSAndroid Build Coastguard Worker DEFINE_OPERATOR(/); 1220*61c4878aSAndroid Build Coastguard Worker DEFINE_OPERATOR(*); 1221*61c4878aSAndroid Build Coastguard Worker 1222*61c4878aSAndroid Build Coastguard Worker #undef DEFINE_OPERATOR 1223*61c4878aSAndroid Build Coastguard Worker 1224*61c4878aSAndroid Build Coastguard WorkerPreprocessor conditional statements 1225*61c4878aSAndroid Build Coastguard Worker=================================== 1226*61c4878aSAndroid Build Coastguard WorkerWhen using macros for conditional compilation, prefer to use ``#if`` over 1227*61c4878aSAndroid Build Coastguard Worker``#ifdef``. This checks the value of the macro rather than whether it exists. 1228*61c4878aSAndroid Build Coastguard Worker 1229*61c4878aSAndroid Build Coastguard Worker* ``#if`` handles undefined macros equivalently to ``#ifdef``. Undefined 1230*61c4878aSAndroid Build Coastguard Worker macros expand to 0 in preprocessor conditional statements. 1231*61c4878aSAndroid Build Coastguard Worker* ``#if`` evaluates false for macros defined as 0, while ``#ifdef`` evaluates 1232*61c4878aSAndroid Build Coastguard Worker true. 1233*61c4878aSAndroid Build Coastguard Worker* Macros defined using compiler flags have a default value of 1 in GCC and 1234*61c4878aSAndroid Build Coastguard Worker Clang, so they work equivalently for ``#if`` and ``#ifdef``. 1235*61c4878aSAndroid Build Coastguard Worker* Macros defined to an empty statement cause compile-time errors in ``#if`` 1236*61c4878aSAndroid Build Coastguard Worker statements, which avoids ambiguity about how the macro should be used. 1237*61c4878aSAndroid Build Coastguard Worker 1238*61c4878aSAndroid Build Coastguard WorkerAll ``#endif`` statements should be commented with the expression from their 1239*61c4878aSAndroid Build Coastguard Workercorresponding ``#if``. Do not indent within preprocessor conditional statements. 1240*61c4878aSAndroid Build Coastguard Worker 1241*61c4878aSAndroid Build Coastguard Worker.. code-block:: cpp 1242*61c4878aSAndroid Build Coastguard Worker 1243*61c4878aSAndroid Build Coastguard Worker #if USE_64_BIT_WORD 1244*61c4878aSAndroid Build Coastguard Worker using Word = uint64_t; 1245*61c4878aSAndroid Build Coastguard Worker #else 1246*61c4878aSAndroid Build Coastguard Worker using Word = uint32_t; 1247*61c4878aSAndroid Build Coastguard Worker #endif // USE_64_BIT_WORD 1248*61c4878aSAndroid Build Coastguard Worker 1249*61c4878aSAndroid Build Coastguard WorkerUnsigned integers 1250*61c4878aSAndroid Build Coastguard Worker================= 1251*61c4878aSAndroid Build Coastguard WorkerUnsigned integers are permitted in Pigweed. Aim for consistency with existing 1252*61c4878aSAndroid Build Coastguard Workercode and the C++ Standard Library. Be very careful mixing signed and unsigned 1253*61c4878aSAndroid Build Coastguard Workerintegers. 1254*61c4878aSAndroid Build Coastguard Worker 1255*61c4878aSAndroid Build Coastguard WorkerFeatures not in the C++ standard 1256*61c4878aSAndroid Build Coastguard Worker================================ 1257*61c4878aSAndroid Build Coastguard WorkerAvoid features not available in standard C++. This includes compiler extensions 1258*61c4878aSAndroid Build Coastguard Workerand features from other standards like POSIX. 1259*61c4878aSAndroid Build Coastguard Worker 1260*61c4878aSAndroid Build Coastguard WorkerFor example, use ``ptrdiff_t`` instead of POSIX's ``ssize_t``, unless 1261*61c4878aSAndroid Build Coastguard Workerinteracting with a POSIX API in intentionally non-portable code. Never use 1262*61c4878aSAndroid Build Coastguard WorkerPOSIX functions with suitable standard or Pigweed alternatives, such as 1263*61c4878aSAndroid Build Coastguard Worker``strnlen`` (use ``pw::string::NullTerminatedLength`` instead). 1264