forked from wpilibsuite/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cppguide.html
2511 lines (2479 loc) · 92 KB
/
cppguide.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>
WPILib C++ Style Guide
</title>
<link rel="stylesheet" type="text/css" href="cppguide.css">
<script language="javascript" src="cppguide.js"></script>
</head>
<body onload="initStyleGuide();">
<div id="content">
<h1>
MisCar's fork of the WPILib C++ Style Guide (Based on the <a
href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.html">Google
C++ Style Guide</a>)
</h1>
<div class="horizontal_toc" id="tocDiv"></div>
<div class="main_body">
<h2 class="ignoreLink" id="Background">
Background
</h2>
<p>
<strong>This guide is a work in progress.</strong> We are currently
working on getting this guide updated to a point where it is useful
for WPILib developers to use.
</p>
<p>
C++ is one of the two main languages (Java being the other) used in
WPILib; in order to maintain consistency and keep the maintenance of
the code manageable, we use this style guide.
</p>
<p>
There are two main overarching purposes to this guide. The first is
to act as a normal C++ style guide (both in terms fo formatting and
programming practices) for C++ developers of WPILib. The other
purpose is to help Java programmers who may know a moderate amount of
C++ but may not be fully up to date with things like C++11 and so may
not even realize that certain C++ features exist.
</p>
<p>
This style guide is a heavily modified version of the <a
href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.html">Google
C++ Style Guide</a>. The Google Style Guide has a lot of good points
and is a good read, but in order to cut the style guide down to a
more readable size and to focus mroe on WPILib-specific information,
we have altetered the original style guide in several ways.
</p>
<p>
One way in which we <em>haven't</em> done much to alter the original
style guide is to keep the vast majority of the
formatting/naming/etc. related information intact. This is both so
that we do not have to write up our own standards and so that
existing tools such as clang-format and the Google eclipse format
configuration files can work out of the box. All of these things
should be relatively non-controversial and do not require much
discussion.
</p>
<p>
Where we deviate more from the original guide is in the style of the
code itself. At the moment (ie, when we first created this modified
version), we deleted all of the sections of the original guide which
mandate particular programming practices such as forbidding
exceptions, multiple inheritance, etc. However, as time goes on, we
gradually add in more information along this lines, either by copying
directly from Google's Style Guide or by writing our own decisions
and best practices, some of which may be very WPILib-specific.
</p>
<p>
As the original guide makes very clear, consistency is extremely
important to keeping the code base manageable, and so we encourage
that, wherever reasonable, that you keep everything consistent with
whatever the standard style is.
</p>
<p>
Along with just C++ style, it is also important to keep in mind that
WPILib consists of both a C++ and Java half. In order to keep things
consistent and easier for users, we ask that, in general, Java and
C++ be kept as consistent with one another as reasonable. This
includes everything from using two spaces for indentation in both
language to keeping the inheritance structure essentially the same in
both. Although the two do not have to be precisely the same, it does
mean that if there is something that you are doing which will be
imposssible to reproduce in some way in Java, then you may want to
reconsider.
</p>
<p>
One final thing to remember is that High School students with
relatively little experience programming are the main user for this
code, and throwing the full brunt of C++ at a student just learning
how to program is likely not the best of ideas. As such, any
user-facing APIs should minimize the use of any more complicated C++
features. As always, use your judgement and ask others in cases where
there is something which may violate anything in this guide.
</p>
<h2 id="Ordering">
Ordering
</h2>
<p>
For consistency with other subteams such as CAD or electronics and pneumatics, and within ourselves, we order
things (in all places) in the following order:
</p>
<ul>
<li>Left comes before right.</li>
<li>Front comes before back.</li>
<li>Small comes before large.</li>
</ul>
<p>
Additionally, the following assumptions are made:
</p>
<ul>
<li>When the robot is said to be at 0 degrees - it is facing the opponent's alliance station.</li>
<li>Counter-clockwise rotation corresponds to positive angle change.</li>
</ul>
<h2 id="Programming_Guidelines">
Programming Guidelines
</h2>
<p>
C++ is a large, complicated language, and in order to ensure that we
stay consistent and maintain certain best practices, we have certain
rules. For the most part these are common sense rules and in some
cases exist solely to point out features of C++ that someone more
familiar with Java may not realize even exist.
</p>
<h3 id="Pointers">
Pointers
</h3>
<p>
In general, we strongly discourage the use of raw pointers in C++
code; instead, references or STL pointers should be used where
appropriate. There are two exceptions to this rule:
</p>
<ul>
<li>When interfacing with lower-level C code or with any libraries
which force you to use raw pointers.
</li>
<li>In order to keep user interfaces consistent, we may keep around
deprecated functions which take raw pointers. Any user-facing
functions which take raw pointers should be deprecated using the
<a href="https://en.wikipedia.org/wiki/C%2B%2B14#The_attribute_.5B.5Bdeprecated.5D.5D">
<code>[[deprecated]]</code></a> attribute and replaced with either
references or STL pointers.
</li>
</ul>
<p>
As of C++11, the following are options in the place of raw pointers:
</p>
<ul>
<li>
<code>std::unique_ptr</code> Should be used when you still need to
use a pointer, but you only need one entity to own the pointer. The
<code>std::unique_ptr</code> will automatically be deleted when
there are no more references to it.
</li>
<li>
<code>std::shared_ptr</code> Should be used when you still need to
use a pointer and you need many references to the object. When
there are zero remaining references to the object, it will be
deleted. Use <code>std::weak_ptr</code> where necessary to avoid
circular dependencies or other potential issues.
</li>
<li>L-value references (the traditional sort of reference that has
been around since before C++11) should be used when you want to pass
around a reference to an object and want to guarantee that it won't
be null. Use const references if you want to avoid copying a large
object but don't want to modify it.
</li>
<li>R-value references were introduced in C++11 and allow for the use
of <code>std::move</code>. R-value references should be used where it
makes sense that a parameter to a function is having its ownership
passed from one place to another. In general, R-value references are
not inherently bad, but they do introduce additional complexity that
may confuse people who are not familiar with them.
</li>
</ul>
<h3 id="Deprecation">
Deprecation
</h3>
<p>
When updating APIs, make liberal use of the
<code>[[deprecated]]</code> attribute (although if it is reasonable
to simply remove any old interfaces then do so) to indicate that
users should no longer use the function. Currently, this will cause
warnings in user code and errors in the WPILib build.
</p>
<pre>
[[deprecated("This is a deprecated function; this text will be displayed when"
" the compiler throws a warning.")]]
void foo() {}
class [[deprecated("This is a deprecated class.")]] Foo {};
int bar [[deprecated("This is a deprecated variable.")]];
</pre>
<p>
See <a href="http://josephmansfield.uk/articles/marking-deprecated-c++14.html">here</a>
for more information on deprecation.
</p>
<h3 id="Implementation_Tradeoffs">
Implementation Tradeoffs
</h3>
<p>
The C++ version of WPILib is intended to be fast, so implementation
tradeoffs should be biased toward that.
</p>
<h3 id="Built-in_Types">
Built-in Types
</h3>
<p>
The HAL uses stdint.h typedefs for integral types since maintaining
consistent sizes on different platforms is important. wpilibc uses
stdint.h typedefs for all integral types except for <code>int</code>
in user-facing interfaces. All integer types are signed in external
interfaces with unsigned types only used for bitwise arithmetic.
</p>
<p>
doubles are used everywhere instead of floats. When compiling with
optimizations enabled, there is negligible performance impact for the
extra precision on ARMv7.
</p>
<h3 id="Error_Handling">
Error Handling
</h3>
<p>
Exceptions should only be thrown for programming (i.e., user) errors.
Runtime errors should be handled internally to avoid crashing the
application.
</p>
<h3 id="Generated_Files">
Generated Files
</h3>
<p>
Since changes would be overwritten upon regeneration, generated files
should not be modified under any circumstances, including for
formatting changes. The generator for those files should be modified
instead. The current list of generated files is represented by
regular expressions in the <code>.styleguide</code> file in the root
directory of the generated file's repository.
</p>
<h2 id="Header_Files">
Header Files
</h2>
<p>
In general, every <code>.cc</code> file should have an associated
<code>.h</code> file. There are some common exceptions, such as
unittests and small <code>.cpp</code> files containing just a
<code>main()</code> function.
</p>
<p>
Correct use of header files can make a huge difference to the
readability, size and performance of your code.
</p>
<p>
The following rules will guide you through the various pitfalls of
using header files.
</p><a id="The_-inl.h_Files"></a>
<h3 id="Self_contained_Headers">
Self-contained Headers
</h3>
<div class="summary">
<p>
Header files should be self-contained and end in <code>.h</code>.
Files that are meant for textual inclusion, but are not headers,
should end in <code>.inc</code>. Separate <code>-inl.h</code>
headers are disallowed.
</p>
</div>
<div class="stylebody">
<p>
All header files should be self-contained. In other words, users
and refactoring tools should not have to adhere to special
conditions in order to include the header. Specifically, a header
should have <a href="#_pragma_once">#pragma once</a>, should
include all other headers it needs, and should not require any
particular symbols to be defined.
</p>
<p>
There are rare cases where a file is not meant to be
self-contained, but instead is meant to be textually included at a
specific point in the code. Examples are files that need to be
included multiple times or platform-specific extensions that
essentially are part of other headers. Such files should use the
file extension <code>.inc</code>.
</p>
<p>
If a template or inline function is declared in a <code>.h</code>
file, define it in that same file. The definitions of these
constructs must be included into every <code>.cc</code> file that
uses them, or the program may fail to link in some build
configurations. Do not move these definitions to separate
<code>-inl.h</code> files.
</p>
<p>
As an exception, a function template that is explicitly
instantiated for all relevant sets of template arguments, or that
is a private member of a class, may be defined in the only
<code>.cc</code> file that instantiates the template.
</p>
</div>
<h3 id="_pragma_once">
#pragma once
</h3>
<div class="summary">
<p>
All header files should have <code>#pragma once</code> at the top
to prevent multiple inclusion.
</p>
</div>
<h3 id="Forward_Declarations">
Forward Declarations
</h3>
<div class="summary">
<p>
You may forward declare ordinary classes in order to avoid
unnecessary <code>#include</code>s.
</p>
</div>
<div class="stylebody">
<div class="definition">
<p>
A "forward declaration" is a declaration of a class, function, or
template without an associated definition. <code>#include</code>
lines can often be replaced with forward declarations of whatever
symbols are actually used by the client code.
</p>
</div>
<div class="pros">
<ul>
<li>Unnecessary <code>#include</code>s force the compiler to open
more files and process more input.
</li>
<li>They can also force your code to be recompiled more often,
due to changes in the header.
</li>
</ul>
</div>
<div class="cons">
<ul>
<li>It can be difficult to determine the correct form of a
forward declaration in the presence of features like templates,
typedefs, default parameters, and using declarations.
</li>
<li>It can be difficult to determine whether a forward
declaration or a full <code>#include</code> is needed for a given
piece of code, particularly when implicit conversion operations
are involved. In extreme cases, replacing an
<code>#include</code> with a forward declaration can silently
change the meaning of code.
</li>
<li>Forward declaring multiple symbols from a header can be more
verbose than simply <code>#include</code>ing the header.
</li>
<li>Forward declarations of functions and templates can prevent
the header owners from making otherwise-compatible changes to
their APIs; for example, widening a parameter type, or adding a
template parameter with a default value.
</li>
<li>Forward declaring symbols from namespace <code>std::</code>
usually yields undefined behavior.
</li>
<li>Structuring code to enable forward declarations (e.g. using
pointer members instead of object members) can make the code
slower and more complex.
</li>
<li>The practical efficiency benefits of forward declarations are
unproven.
</li>
</ul>
</div>
<div class="decision">
<ul>
<li>When using a function declared in a header file, always
<code>#include</code> that header.
</li>
<li>When using a class template, prefer to <code>#include</code>
its header file.
</li>
<li>When using an ordinary class, relying on a forward
declaration is OK, but be wary of situations where a forward
declaration may be insufficient or incorrect; when in doubt, just
<code>#include</code> the appropriate header.
</li>
<li>Do not replace data members with pointers just to avoid an
<code>#include</code>.
</li>
</ul>
<p>
Please see <a href="#Names_and_Order_of_Includes">Names and Order
of Includes</a> for rules about when to #include a header.
</p>
</div>
</div>
<h3 id="Inline_Functions">
Inline Functions
</h3>
<div class="summary">
<p>
Define functions inline only when they are small, say, 10 lines or
less.
</p>
</div>
<div class="stylebody">
<div class="definition">
<p>
You can declare functions in a way that allows the compiler to
expand them inline rather than calling them through the usual
function call mechanism.
</p>
</div>
<div class="pros">
<p>
Inlining a function can generate more efficient object code, as
long as the inlined function is small. Feel free to inline
accessors and mutators, and other short, performance-critical
functions.
</p>
</div>
<div class="cons">
<p>
Overuse of inlining can actually make programs slower. Depending
on a function's size, inlining it can cause the code size to
increase or decrease. Inlining a very small accessor function
will usually decrease code size while inlining a very large
function can dramatically increase code size. On modern
processors smaller code usually runs faster due to better use of
the instruction cache.
</p>
</div>
<div class="decision">
<p>
A decent rule of thumb is to not inline a function if it is more
than 10 lines long. Beware of destructors, which are often longer
than they appear because of implicit member- and base-destructor
calls!
</p>
<p>
Another useful rule of thumb: it's typically not cost effective
to inline functions with loops or switch statements (unless, in
the common case, the loop or switch statement is never executed).
</p>
<p>
It is important to know that functions are not always inlined
even if they are declared as such; for example, virtual and
recursive functions are not normally inlined. Usually recursive
functions should not be inline. The main reason for making a
virtual function inline is to place its definition in the class,
either for convenience or to document its behavior, e.g., for
accessors and mutators.
</p>
</div>
</div>
<h3 id="Function_Parameter_Ordering">
Function Parameter Ordering
</h3>
<div class="summary">
<p>
When defining a function, parameter order is: inputs, then outputs.
</p>
</div>
<div class="stylebody">
<p>
Parameters to C/C++ functions are either input to the function,
output from the function, or both. Input parameters are usually
values or <code>const</code> references, while output and
input/output parameters will be non-<code>const</code> pointers.
Constructors may use non-<code>const</code> reference parameters
for class types, but not built-in types. In other words, do not use
non-<code>const</code> reference output parameters. When ordering
function parameters, put all input-only parameters before any
output parameters. In particular, do not add new parameters to the
end of the function just because they are new; place new input-only
parameters before the output parameters.
</p>
<p>
This is not a hard-and-fast rule. Parameters that are both input
and output (often classes/structs) muddy the waters, and, as
always, consistency with related functions may require you to bend
the rule.
</p>
</div>
<h3 id="Names_and_Order_of_Includes">
Names and Order of Includes
</h3>
<div class="summary">
<p>
Use standard order for readability and to avoid hidden
dependencies: Related header, C library, C++ library, other
libraries' <code>.h</code>, your project's <code>.h</code>.
</p>
</div>
<div class="stylebody">
<p>
All of a project's header files should be listed as descendants of
the project's source directory without use of UNIX directory
shortcuts <code>.</code> (the current directory) or <code>..</code>
(the parent directory). For example,
<code>google-awesome-project/src/base/logging.h</code> should be
included as:
</p>
<pre>#include "base/logging.h"
</pre>
<p>
In <code><var>dir/foo</var>.cc</code> or
<code><var>dir/foo_test</var>.cc</code>, whose main purpose is to
implement or test the stuff in <code><var>dir2/foo2</var>.h</code>,
order your includes as follows:
</p>
<ol>
<li>
<code><var>dir2/foo2</var>.h</code>.
</li>
<li>C system files.
</li>
<li>C++ system files.
</li>
<li>Other libraries' <code>.h</code> files.
</li>
<li>Your project's <code>.h</code> files.
</li>
</ol>
<p>
C and C++ standard library includes are considered system files in
their respective group. Includes within one group should not have
an empty line separating them, while there should be an empty line
between groups.
</p>
<p>
With the preferred ordering, if <code><var>dir2/foo2</var>.h</code>
omits any necessary includes, the build of
<code><var>dir/foo</var>.cc</code> or
<code><var>dir/foo</var>_test.cc</code> will break. Thus, this rule
ensures that build breaks show up first for the people working on
these files, not for innocent people in other packages.
</p>
<p>
<code><var>dir/foo</var>.cc</code> and
<code><var>dir2/foo2</var>.h</code> are usually in the same
directory (e.g. <code>base/basictypes_test.cc</code> and
<code>base/basictypes.h</code>), but may sometimes be in different
directories too.
</p>
<p>
Within each section the includes should be ordered alphabetically.
Note that older code might not conform to this rule and should be
fixed when convenient.
</p>
<p>
You should include all the headers that define the symbols you rely
upon (except in cases of <a href="#Forward_Declarations">forward
declaration</a>). If you rely on symbols from <code>bar.h</code>,
don't count on the fact that you included <code>foo.h</code> which
(currently) includes <code>bar.h</code>: include <code>bar.h</code>
yourself, unless <code>foo.h</code> explicitly demonstrates its
intent to provide you the symbols of <code>bar.h</code>. However,
any includes present in the related header do not need to be
included again in the related <code>cc</code> (i.e.,
<code>foo.cc</code> can rely on <code>foo.h</code>'s includes).
</p>
<p>
For example, the includes in
<code>google-awesome-project/src/foo/internal/fooserver.cc</code>
might look like this:
</p>
<pre>#include "foo/server/fooserver.h"
#include <sys/types.h>
#include <unistd.h>
#include <hash_map>
#include <vector>
#include "base/basictypes.h"
#include "base/commandlineflags.h"
#include "foo/server/bar.h"
</pre>
<p class="exception">
Sometimes, system-specific code needs conditional includes. Such
code can put conditional includes after other includes. Of course,
keep your system-specific code small and localized. Example:
</p>
<pre>#include "foo/public/fooserver.h"
#include "base/port.h" // For LANG_CXX11.
#ifdef LANG_CXX11
#include <initializer_list>
#endif // LANG_CXX11
</pre>
</div>
<h2 id="Naming">
Naming
</h2>
<p>
The most important consistency rules are those that govern naming.
The style of a name immediately informs us what sort of thing the
named entity is: a type, a variable, a function, a constant, a macro,
etc., without requiring us to search for the declaration of that
entity. The pattern-matching engine in our brains relies a great deal
on these naming rules.
</p>
<p>
Naming rules are pretty arbitrary, but we feel that consistency is
more important than individual preferences in this area, so
regardless of whether you find them sensible or not, the rules are
the rules.
</p>
<h3 id="General_Naming_Rules">
General Naming Rules
</h3>
<div class="summary">
<p>
Function names, variable names, and filenames should be
descriptive; eschew abbreviation.
</p>
</div>
<div class="stylebody">
<p>
Give as descriptive a name as possible, within reason. Do not worry
about saving horizontal space as it is far more important to make
your code immediately understandable by a new reader. Do not use
abbreviations that are ambiguous or unfamiliar to readers outside
your project, and do not abbreviate by deleting letters within a
word.
</p>
<pre>int price_count_reader; // No abbreviation.
int num_errors; // "num" is a widespread convention.
int num_dns_connections; // Most people know what "DNS" stands for.
</pre>
<pre class="badcode">int n; // Meaningless.
int nerr; // Ambiguous abbreviation.
int n_comp_conns; // Ambiguous abbreviation.
int wgc_connections; // Only your group knows what this stands for.
int pc_reader; // Lots of things can be abbreviated "pc".
int cstmr_id; // Deletes internal letters.
</pre>
</div>
<h3 id="File_Names">
File Names
</h3>
<div class="summary">
<p>
Filenames should be all lowercase and can include underscores
(<code>_</code>) or dashes (<code>-</code>). Follow the convention
that your project uses. If there is no consistent local pattern to
follow, prefer "_".
</p>
</div>
<div class="stylebody">
<p>
Examples of acceptable file names:
</p>
<ul>
<li>
<code>my_useful_class.cc</code>
</li>
<li>
<code>my-useful-class.cc</code>
</li>
<li>
<code>myusefulclass.cc</code>
</li>
<li>
<code>myusefulclass_test.cc // _unittest and _regtest are
deprecated.</code>
</li>
</ul>
<p>
C++ files should end in <code>.cc</code> and header files should
end in <code>.h</code>. Files that rely on being textually included
at specific points should end in <code>.inc</code> (see also the
section on <a href="#Self_contained_Headers">self-contained
headers</a>).
</p>
<p>
Do not use filenames that already exist in
<code>/usr/include</code>, such as <code>db.h</code>.
</p>
<p>
In general, make your filenames very specific. For example, use
<code>http_server_logs.h</code> rather than <code>logs.h</code>. A
very common case is to have a pair of files called, e.g.,
<code>foo_bar.h</code> and <code>foo_bar.cc</code>, defining a
class called <code>FooBar</code>.
</p>
<p>
Inline functions must be in a <code>.h</code> file. If your inline
functions are very short, they should go directly into your
<code>.h</code> file.
</p>
</div>
<h3 id="Type_Names">
Type Names
</h3>
<div class="summary">
<p>
Type names start with a capital letter and have a capital letter
for each new word, with no underscores:
<code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.
</p>
</div>
<div class="stylebody">
<p>
The names of all types — classes, structs, typedefs, and enums —
have the same naming convention. Type names should start with a
capital letter and have a capital letter for each new word. No
underscores. For example:
</p>
<pre>// classes and structs
class UrlTable { ...
class UrlTableTester { ...
struct UrlTableProperties { ...
// typedefs
typedef hash_map<UrlTableProperties *, string> PropertiesMap;
// enums
enum UrlTableErrors { ...
</pre>
</div>
<h3 id="Variable_Names">
Variable Names
</h3>
<div class="summary">
<p>
The names of variables and data members are all lowercase, with
underscores between words. Data members of classes (but not
structs) additionally are prefixed with "m_". For instance:
<code>a_local_variable</code>, <code>a_struct_data_member</code>,
<code>m_a_class_data_member</code>.
</p>
</div>
<div class="stylebody">
<h4 class="stylepoint_subsection">
Common Variable names
</h4>
<p>
For example:
</p>
<pre>string table_name; // OK - uses underscore.
string tablename; // OK - all lowercase.
</pre>
<pre class="badcode">string tableName; // Bad - mixed case.
</pre>
<h4 class="stylepoint_subsection">
Class Data Members
</h4>
<p>
Data members of classes, both static and non-static, are named like
ordinary nonmember variables, but prefixed with a "m_".
</p>
<pre>class TableInfo {
...
private:
string m_table_name; // OK - m_ at beginning.
string m_tablename; // OK.
static Pool<TableInfo>* m_pool; // OK.
};
</pre>
<h4 class="stylepoint_subsection">
Struct Data Members
</h4>
<p>
Data members of structs, both static and non-static, are named like
ordinary nonmember variables. They do not have the preceding "m_"
that data members in classes have.
</p>
<pre>struct UrlTableProperties {
string name;
int num_entries;
static Pool<UrlTableProperties>* pool;
};
</pre>
<p>
See <a href="#Structs_vs._Classes">Structs vs. Classes</a> for a
discussion of when to use a struct versus a class.
</p>
<h4 class="stylepoint_subsection">
Global Variables
</h4>
<p>
There are no special requirements for global variables, which
should be rare in any case, but if you use one, consider prefixing
it with <code>g_</code> or some other marker to easily distinguish
it from local variables.
</p>
</div>
<h3 id="Constant_Names">
Constant Names
</h3>
<div class="summary">
<p>
Use a <code>k</code> followed by mixed case, e.g.,
<code>kDaysInAWeek</code>, for constants defined globally or within
a class.
</p>
</div>
<div class="stylebody">
<p>
As a convenience to the reader, compile-time constants of global or
class scope follow a different naming convention from other
variables. Use a <code>k</code> followed by words with uppercase
first letters:
</p>
<pre>const int kDaysInAWeek = 7;
</pre>
<p>
This convention may optionally be used for compile-time constants
of local scope; otherwise the usual variable naming rules apply.
</p>
</div>
<h3 id="Function_Names">
Function Names
</h3>
<div class="summary">
<p>
Regular functions have mixed case; accessors and mutators match the
name of the variable: <code>MyExcitingFunction()</code>,
<code>MyExcitingMethod()</code>,
<code>my_exciting_member_variable()</code>,
<code>set_my_exciting_member_variable()</code>.
</p>
</div>
<div class="stylebody">
<h4 class="stylepoint_subsection">
Regular Functions
</h4>
<p>
Functions should start with a capital letter and have a capital
letter for each new word. No underscores.
</p>
<p>
If your function crashes upon an error, you should append OrDie to
the function name. This only applies to functions which could be
used by production code and to errors that are reasonably likely to
occur during normal operation.
</p>
<pre>AddTableEntry()
DeleteUrl()
OpenFileOrDie()
</pre>
<h4 class="stylepoint_subsection">
Accessors and Mutators
</h4>
<p>
Accessors and mutators (get and set functions) should match the
name of the variable they are getting and setting. This shows an
excerpt of a class whose instance variable is
<code>num_entries_</code>.
</p>
<pre>class MyClass {
public:
...
int num_entries() const { return num_entries_; }
void set_num_entries(int num_entries) { num_entries_ = num_entries; }
private:
int num_entries_;
};
</pre>
<p>
You may also use lowercase letters for other very short inlined
functions. For example if a function were so cheap you would not
cache the value if you were calling it in a loop, then lowercase
naming would be acceptable.
</p>
</div>
<h3 id="Namespace_Names">
Namespace Names
</h3>
<div class="summary">
<p>
Namespace names are all lower-case, and based on project names and
possibly their directory structure:
<code>google_awesome_project</code>.
</p>
</div>
<div class="stylebody">
<p>
See <a href="#Namespaces">Namespaces</a> for a discussion of
namespaces and how to name them.
</p>
</div>
<h3 id="Enumerator_Names">
Enumerator Names
</h3>
<div class="summary">
<p>
Enumerators should be named like <a href="#Constant_Names">constants</a>: <code>kEnumName</code>.
</p>
</div>
<div class="stylebody">
<p>
The enumeration name, <code>UrlTableErrors</code> (and
<code>AlternateUrlTableErrors</code>), is a type, and therefore
mixed case.
</p>
<pre>enum UrlTableErrors {
kOK = 0,
kErrorOutOfMemory,
kErrorMalformedInput,
};
</pre>
</div>
<h3 id="Macro_Names">
Macro Names
</h3>
<div class="summary">
<p>
You're not really going to <a href="#Preprocessor_Macros">define a
macro</a>, are you? If you do, they're like this:
<code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN</code>.
</p>
</div>
<div class="stylebody">
<p>
Please see the <a href="#Preprocessor_Macros">description of
macros</a>; in general macros should <em>not</em> be used. However,
if they are absolutely needed, then they should be named with all
capitals and underscores.
</p>
<pre>#define ROUND(x) ...
#define PI_ROUNDED 3.0
</pre>
</div>
<h3 id="Exceptions_to_Naming_Rules">
Exceptions to Naming Rules
</h3>
<div class="summary">
<p>
If you are naming something that is analogous to an existing C or
C++ entity then you can follow the existing naming convention
scheme.
</p>
</div>
<div class="stylebody">
<dl>
<dt>
<code>bigopen()</code>
</dt>
<dd>
function name, follows form of <code>open()</code>
</dd>
<dt>
<code>uint</code>
</dt>
<dd>
<code>typedef</code>
</dd>
<dt>
<code>bigpos</code>
</dt>
<dd>
<code>struct</code> or <code>class</code>, follows form of
<code>pos</code>
</dd>
<dt>
<code>sparse_hash_map</code>
</dt>
<dd>
STL-like entity; follows STL naming conventions
</dd>
<dt>
<code>LONGLONG_MAX</code>
</dt>
<dd>
a constant, as in <code>INT_MAX</code>
</dd>
</dl>
</div>
<h2 id="Comments">
Comments
</h2>
<p>
Though a pain to write, comments are absolutely vital to keeping our
code readable. The following rules describe what you should comment
and where. But remember: while comments are very important, the best
code is self-documenting. Giving sensible names to types and
variables is much better than using obscure names that you must then
explain through comments.
</p>
<p>
When writing your comments, write for your audience: the next
contributor who will need to understand your code. Be generous — the
next one may be you!
</p>
<h3 id="Comment_Style">
Comment Style
</h3>
<div class="summary">
<p>
Use either the <code>//</code> or <code>/* */</code> syntax, as
long as you are consistent.
</p>
</div>
<div class="stylebody">
<p>
You can use either the <code>//</code> or the <code>/* */</code>
syntax; however, <code>//</code> is <em>much</em> more common. Be
consistent with how you comment and what style you use where.
</p>