CPP-Styleguide

C++ Styleguide

Disclaimer

This is my own styleguide, meant mainly for me. You don’t have to agree or follow anything that’s written here.

Formatting

Function Braces (1)

The opening brace of a function should be placed on the same line as the function definition, separated by a space from the class definition. The closing brace should be placed on the line following the last line of the function.

void main() {
    // do something
    return 0;
}

Function Braces (2)

Braces should not be used for a function if you are only declaring the signature.

void main();

Identation (1)

Identation should be done using TABS.

File Format (1)

Files should be formatted with UTF-8 and LF, regardless of operating system. Only exception is Powershell scripts, which should use UTF-8+BOM and CRLF.

Pointer Management (1)

Avoid smart pointers unless:

Pointer Management (2)

Use alloca() whenever you need to store basic types such as integers, but don’t know EXACTLY how many there are. Make sure to never allocate too much memory with alloca() or you’ll run into Stack overflow errors. If you get a stack overflow error, always take a look at your alloca() calls and try logging the amount of memory you allocate each time and in total on each line.
Use malloc() (or, better yet, new) whenever you can’t use alloca() (long loops, large memory, types that have deconstructors).

Pointer Management (3)

Store pointers as:

Building

Position-Independent

All output binaries should be as position-independent as possible, regardless of usecase. (Excluding kernel-level programming, or binaries where size is a priority)
On Linux, position-independent binaries should be made with the use of -fPIC or -fPIE -pie flags for g++.

Debug Builds

Debug builds should be built with the following arguments:

Stack size

For builds making excessive use of alloca(), consider giving them a bigger stack size.

Naming

Naming conventions that should be used:

Temporary variables must start with an underscore, or end in _tmp.

Reproducibility

For the sake of reproducibility, only use compilers that are part of the GNU compiler set (gcc/g++/ld/nasm).

UB

UB (Undefined Behaviour) is a scary topic for everyone.
You shouldn’t avoid it. You should understand what happens when you run different mechanisms that cause ‘UB’, and you should avoid behaviour that is unpredictable/unexpected/error-prone/unreproducible.
Understanding the compiler is always better than fearing the compiler.