RidgeRun Developer Manual - Coding Styles - C++

From RidgeRun Developer Connection
< RidgeRun Developer Manual‎ | Coding Styles
Revision as of 10:10, 7 June 2021 by Efernandez (talk | contribs) (Other good practices)
Jump to: navigation, search




Previous: Coding Styles/C Index Next: Coding Styles/Python




Introduction to 'C++' Coding Styles

When writing software source code there are many coding styles as the concept covers a lot of aspects (some of them subjective). In general RidgeRun tries to follow the Google C++ Style Guide.

Good practices

Conditionals

if ( nullptr == var ) {
  // ...
}

This is to avoid possible bugs like:

if ( var = nullptr ) {
  // ...
}

A derived good practice is to use const keyword as much as you can:

const int val = 1;

if (val = 2) { // This should not compile
    ...
}

Header ordering

For header ordering we use an inside-out approach, this is, the local header goes first and the system headers go last so the header inclusion shoul go as follows:


1. Header file defining the functions implemented in the source file.

2. Other headers from the same project

3. Headers from non-standard projects

4. System headers (with angle brackets and .h extension)

5. C++ standard headers (with angle brackets without an extension)


A blank line should be added between each block of headers and the headers should go in alphabetical order in each block.

In an ideal world, header files should be self-contained and the include order shouldn't matter, however, this is not always the case, and if the order matters is a sign something is wrong in your code. Having the header file declaring the functions in the source file as the first include helps make sure my header is in fact self-contained. If it shows any error is a sign something is wrong.

Also, if an out-of-order include is needed it is a sign that something is not right in either your code or the external headers. If the problem is in your code, the best thing to do is to fix it but if not, the reason for the out-of-order include should be very well documented.

Here is an example of how the includes should look.

#include "my_module.h"

#include "other_header.h"

#include <sys/types.h>
#include <unistd.h>

#include <string>
#include <vector>


Previous: Coding Styles/C Index Next: Coding Styles/Python