Google C++ Style Quick Reference
A concise summary of essential Google C++ style guidelines to elevate your code quality.
https://google.github.io/styleguide/cppguide.html
1. Naming Conventions
Type | Convention | Example |
---|---|---|
Namespaces | snake_case |
namespace image_processing |
Class/Struct/Enum/Type Names | CamelCase |
class AudioEncoder |
Public Functions | CamelCase |
void ComputeValue() |
Private/Protected Functions | CamelCase (same as public) |
void UpdateInternalState() |
Local Variables | snake_case |
int local_count; |
Public Member Variables (if used) | snake_case |
int frame_count; |
Private/Protected Member Variables | snake_case_ (with trailing underscore) |
int buffer_size_; |
Static Member Variables | snake_case_ (with trailing underscore) |
static int instance_count_; |
Constants (constexpr , const ) |
kCamelCase |
const int kMaxWidth = 800; |
Macros | ALL_CAPS_WITH_UNDERSCORES |
#define BUFFER_SIZE 256 |
Enumerators (enum values) | kCamelCase |
enum Color { kRed, kGreen, kBlue }; |
Template Parameters | CamelCase |
template <typename InputIterator> |
Files | snake_case.h / snake_case.cc |
audio_encoder.h , audio_encoder.cc |
2. Formatting
- Only use spaces(no tab). Use 2 spaces at a time.
- Maximum of 80 characters for each line.
- Pointers and references:
int* p
andint& r
.
Formatting could be easily resolved using clang-format
. Create a .clang-format
file in your project’s root directory.
1 | BasedOnStyle: Google |
And run the following command line to apply the format.
1 | clang-format -i file1.cpp |
3. Include Files
- Orders: Related header -> C system headers -> C++ standard library headers -> other libraries’ headers -> your project’s headers.
- All project’s header files need to be listed as descendants of the project’s source directory. No
.
or..
.
1 |
4. Classes and Structs
- Use a struct only for passive objects that carry data; everything else is a class.
- Explicitly declare constructors as
explicit
if they take a single argument.
5. Const Correctness
Mark member functions as const
if they do not modify object state.
6. Lambda Expressions
Prefer explicit capture over [=]
or [&]
to avoid accidental capture.
7. Defining Functions in Headers
Functions defined at the point of declaration are inline
by default.
Based on the guide, there are PROs and CONs doing that. The rule is: the definition has 10 lines or fewer.
Adding More
Google C++ Style Quick Reference
http://chuzcjoe.github.io/cpp/cpp-google-cpp-style-guideline/